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.
You didn't pass the ID of the Message you want to mark as unread. Pass it on your AJAX function as well: