I must admit enjoying ASP.NET MVC. Ajax is a must for all modern and respectable websites so I ended up using it over and over again. This little set of code snippet happened so often that I decided to write it down somewhere.

First, you will need to have an HTML element like for example a div that will contain a partial view:

<div id="mydiv">
<% Html.RenderPartial("MyPartialView", Model); %>

This div is going to be updated by the Ajax-executed code. Second, the partial view will contain the Ajax.BeginForm() code needs to look like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyModel>" %>
<% using (Ajax.BeginForm("AjaxActionName", "MyActionName", new AjaxOptions{ UpdateTargetId = "mydiv" })) { %>
<input id="input1" type="text" /> <input id="input2" type="text" />
<input id="dosomething" type="submit" value="save" />
<span>The Answer is: <%= Html.Encode(Model.Count()) %></span>
<% } %>

Take note that input1 and input2 are provided by the user and the result of the website is shown in the span. Finally, there should be a controller like the following:

public PartialViewResult MyActionName(string input1, string input2)
return PartialView("MyPartialView", DataHandling(input1, input2));

When the user clicks on ‘dosomething’ button, an Ajax call to ‘MyActionName’ action is made. The action handles the user inputs and updates ‘mydiv’  with the a new instance of ‘MyPartialView’. Only this time, ‘MyModel’ object passed to the partial view is the result of the website handling ‘input1′ and ‘input2′ from the user.

3 thoughts on “ASP.NET MVC Ajax.BeginForm Sample Code

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>