Reputation: 2030
Controller:
public ActionResult Edit(string temp)
{
ViewBag.Time = DateTime.Now.ToString("hh:mm:ss");
return PartialView("Edit");
}
Partial View:
@using (Ajax.BeginForm("Edit", "Home", new AjaxOptions{UpdateTargetId = "mydiv"}))
{
<input type="submit" value="Save" />
}
Index View (part of contents)
<div id="mydiv">
<span>The Time is: @ViewBag.Time</span>
</div>
@Html.Partial("Edit")
ClientValidationEnabled
and UnobtrusiveJavaScriptEnabled
are true
jquery.validate.min.js
, jquery.validate.unobtrusive.min.js
, jquery.unobtrusive-ajax.min.js
, MicrosoftMvcAjax.js
and MicrosoftAjax.js
are added
At first, the time is shown correctly. When the Save button is clicked for the first time, time disappears and Save button is shown twice and then nothing happens except calling the Action on clicking on both buttons.
Upvotes: 1
Views: 8564
Reputation: 2346
You have things kind of backwards. Try this:
Controller
public ActionResult Edit(string temp)
{
ViewBag.Time = DateTime.Now.ToString("hh:mm:ss");
return PartialView("Edit");
}
Index View
@using (Ajax.BeginForm("Edit", "Home", new AjaxOptions{UpdateTargetId = "mydiv"}))
{
<input type="submit" value="Save" />
}
@Html.Action("Edit")
Partial View (Edit)
<div id="mydiv">
<span>The Time is: @ViewBag.Time</span>
</div>
The ViewBag is only accessable at runtime (when the page initially loads) so this means if you fetch data via ajax, the viewbag in the controller action is only accessable to the partial view of that controller action (and not index.cshtml which called the action via ajax). In short (tl;dr) to be able to use the viewbag which you set in Edit action, you need to use it in the returning partialview. (and not anywhere else, because the content isnt re-rendered by the razor engine)
Upvotes: 2
Reputation: 1341
I set things up like so.
Very simple, but I noticed the person posting the question and the answer had no insertion mode so I posted this lame bit of code :)
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "the div youwant to update / replace"
}
Upvotes: -1