Reputation: 129
I've been searching for informations on how to use AJAX in MVC projects and so far it just confused me a bit. I belive I'm not too far now to implement an Ajax ActionLink that causes a database entry to change and so this change gets reflected to the view. But clearly, this bit of code is wrong right now:
public void MarkAsRead(Models.MessageModel message)
{
using (var db = new MessengerDBEntities())
{
var dbMessage = db.Messages.FirstOrDefault(m => m.messageID == message.Id);
// Error handling
if (dbMessage == null)
{
ViewBag.ResultMessage =
"Something bad has happened with that message in the meantime. Please log out and in again.";
return;
}
dbMessage.messageRead = true;
db.SaveChanges();
return;
}
}
This is the Razor code:
@if (Model.Count() > 0)
{
<br /><br />
string messageClass;
foreach (var message in Model)
{
messageClass = message.Read ? "message-header" : "message-unread-header";
<div class="message-container">
<div class="@messageClass">
@if (!message.Read)
{
<text>New </text>
}
From: @message.Sender
@if(!message.Read)
{
<span class="mark-read-span">
@Ajax.ActionLink("Mark as read", "MarkAsRead", message, new AjaxOptions())
</span>
}
</div>
<div class="message-mainbody">
@message.Content
</div>
<div class="message-footer">
At: @message.Timestamp.ToShortDateString() @message.Timestamp.ToShortTimeString()
</div>
</div>
<br />
}
}
else
{
<div id="no-messages-div">You haven't got any messages yet. :(</div>
}
In the view, I'm iterating through a collection of objects (received messages). For each message, I check if it has been read yet, and if it's not, there goes a link that tilt it to read state. I also assign a different class to the div that shows the message based on wheather it's a new message or not:
@messageClass = message.Read ? "message-header" : "message-unread-header";
<div class="message-container">
<div class="@messageClass">
...
I'm suspecting that I use the Ajax.ActionLink helper with wrong AjaxOptions parameter, but I didn't get closer to the solution after reading MSDN about it. What could I do wrong with this?
Upvotes: 0
Views: 669
Reputation: 169
What you can do here is, try to use the ID of the messages.
You should know that in MVC route is defined as Controller/Action/id
So, if you pass the ID of the message to the Action then you can change the message status in the Database. For example:
public ActionResult Message(long messageid)
{
// do you stuff to the message here in the database
// then return view or partial view whatever you want
return View();
}
The correct syntax for the Ajax.ActionLink function call it:
@Ajax.ActionLink("You Link Name", "ActionName", "ControllerName", new { ID = @Message.ID }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "update-div-ID", InsertionMode = InsertionMode.Replace })
In the above call, I was returning a partial view and displaying that in Div with ID "update-div-ID". You need to take care of AjaxOptions like this.
Upvotes: 0