Hi, is it possible to use Ajax with ASP.NET MVC 2 to reload a user control, pass along a new Model and have it update all the values that make use of this model without refreshing the rest of the site content?
A:
Yes, and here is one way to do so:
You can call an action on a controller from ajax (jquery is what I use) and get the result. To pass data up you provide parameter values to the $.ajax() call and rendering back you just render a partial with whatever viewmodel is appropriate to your partial.
To get the content displayed you just take the HTML result passed back to your $.ajax() call and, most commonly, replace the contents of a div with your HTML result.
Tahbaza
2010-08-17 02:59:50
Hi Tahbaza! Thanks for your quick reply! That sounds like something I would need!Could you provide some sample code to illustrate this please? What would have to be in my View? My controller looks like this:[Authorize, HttpGet]public ActionResult UpdateAvondeten(FormCollection formValues){ if (Request.IsAjaxRequest()) { Avondeten avondeten = avondetenRepository.GetAvondeten(Convert.ToInt32(formValues["Datum"])); return PartialView("DeclaratieWidget", avondeten); } else { return RedirectToAction("Foutmelding", "Home"); }}
Erwin1441
2010-08-17 07:31:48
A:
I got it working!
I have the following code in the Controller:
[Authorize, HttpPost]
public ActionResult UpdateDinner(FormCollection formValues)
{
if (Request.IsAjaxRequest())
{
Dinner Dinner = DinnerRepository.GetDinner(Convert.ToInt32(formValues["Date"]));
return PartialView("DeclaratieWidget", Dinner);
}
}
I have this code in my View:
<script src="<%= AppPathHelper.Url(Request.ApplicationPath, "/Scripts/MicrosoftAjax.debug.js") %>" type="text/javascript"></script>
<script src="<%= AppPathHelper.Url(Request.ApplicationPath, "/Scripts/MicrosoftMvcAjax.debug.js") %>" type="text/javascript"></script>
<% using (Ajax.BeginForm("UpdateDinner", new AjaxOptions { UpdateTargetId = "Dinner" }))
{ %>
<select id="Date" name="Date">
<option value="<%= Dinner.Dinner_ID %>"><%= Dinner.Date.ToString("dddd d MMMM") %></option>
</select>
<input type="submit" value="Delete" />
<div id="avondeten">
<% Html.RenderPartial("DeclaratieWidget", Model.Dinners[0]); %>
</div>
It works perfectly this way! :D
Erwin1441
2010-08-17 11:35:42
Congratulations on getting something working before I could respond; veel geluk!
Tahbaza
2010-08-17 17:19:26