Change DB value when clicking on CheckBoxFor using MVC

352 views Asked by At

This is my first question on SO, so please have a heart. I'm working on a project to make messages able to be marked as unread. When the the user clicks on details it marks the message as read, but I am trying to use a CheckBoxFor to allow the user to mark the message as unread. Here is my attempt after researching thoroughly. I cannot seem to get the message to be marked unread when I go back out to the main view.

Here is the CheckBoxFor in Details.cshtml:

<dd>
     @Html.CheckBoxFor(model => model.UnreadMessage, new { onclick = "UpdateUnreadMessage(this)" })
</dd>

And the jQuery call to determine the status of the CheckBoxFor:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function UpdateUnreadMessage(elem) {
    var UnreadMessage = $(elem).is(':checked');
    $.ajax({
        type: 'POST',
        url: "@Url.Action("UpdateUnreadMessage", "Details")",
        data: { check: UnreadMessage,},
        success: function (res) {
            console.log(res);
        },
        dataType: 'json'
    });
}
</script>

And here is the POST method in the MessageController:

// POST: Message/Details/5
[HttpPost]
public ActionResult UpdateUnreadMessage(bool check, Guid? id)
{
    Message message = db.Messages.Find(id);
    if (check == true)
    {
        message.UnreadMessage = true;
    };
    db.SaveChanges();
    return View();
}

Can someone please help me figure out what I am doing wrong? I greatly appreciate it.

3

There are 3 answers

1
Willy David Jr On

You didn't pass the ID of the Message you want to mark as unread. Pass it on your AJAX function as well:

data: { check: UnreadMessage, id: YourVariableIDHere },
0
prabhu379 On

If POST method in the MessageController then update url as

url: "@Url.Action("UpdateUnreadMessage", "Message")"

0
Nick On

So I was able to solve what was happening. I did need to pass through the ID. Here's how I was able to get it to work.

CSHTML:

<dd>@Html.CheckBoxFor(model => model.UnreadMessage, new { id = "UnreadCheckBox" })</dd>

SCRIPT:

<script>
$("#UnreadCheckBox").change(function () {
    var UnreadMessage = $(this).is(':checked');
    $.ajax({
        type: 'POST',
        url: "@Url.Action("UpdateUnreadMessage", "Message")",
        data: { check: UnreadMessage, id: '@Model.MessageID' },
        success: function (res) {
            console.log(res);
        },
    });
});

And finally in the CONTROLLER:

        public ActionResult UpdateUnreadMessage(bool check, Guid? id)
    {
        Message message = db.Messages.Find(id);
        if (check == true)
        {
            message.UnreadMessage = true;
        }
        else{
            message.UnreadMessage = false;
        }
        db.SaveChanges();
        return Content("Succesful Update");
    }

Thank you everyone for all of your help and suggestions.