Using Partial Views with ASP.NET MVC AJAX
One thing I struggled to figure-out when I moved to ASP.NET MVC was how to work with its AJAX model. I was used to work with UpdatePanels and the Ajax Community Tookit that are event-based WebForms controls. Especially for someone who was used to deal with the rich set of controls from Ajax Community Toolkit, it was hard to have nothing more than basically two Ajax function: Ajax.ActionLink() and Ajax.BeginForm(). Well believe it or not, ASP.NET MVC Ajax model ended-up working quite well for me, as the secret lies in Partial Views. That makes a lot of sense since Ajax is all about updating part of a web page. The only hard thing was that I had to get used to ASP.NET MVC’s paradigm shift from event-based WebForms.
So this is typically the way I work. First, I create a partial view and add the Ajax code in it:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyNamespace.MyModel>" %> <%= Html.Encode(Model.ValueToDisplay) %> <%= Ajax.ActionLink("ActionText", "ActionName", new { id = Model.id, controller = "ControllerID" }, new AjaxOptions { UpdateTargetId = Model.id.ToString() })%>
Now, the trick is that this PartialView is placed in a HTML div that’s id is equal to Model.id, which should make the page look like this:
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<MyNamespace.MyModel>" %> <div id="<%= Model.id %>"> <% Html.RenderPartial("ThePartialViewAbove", Model); %> </div>
The Controller Action should look like this:
public PartialViewResult Edit(string id) { MyModel cmt; // Put data query code here for cmt return PartialView("ThePartialViewAbove", cmt); }
Now, what happens is that when the Edit action is called (i.e. when the Ajax.ActionLink is clicked), the Model.id div is refreshed with the content of ThePartialViewAbove, which is based on updated data in Edit action. Wow, that’s easy. I love it.

Posted by Ahmad Barirani in