ASP.NET MVC Ajax.BeginForm Sample Code

Posted Posted by Ahmad Barirani in Blog     Comments 3 comments
Nov
11

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); %>
</div>

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:

[AcceptVerbs(HttpVerbs.Post)]
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 Comments to “ASP.NET MVC Ajax.BeginForm Sample Code”

Post comment

About Singular Technologies

Location: Montreal, Canada

Services: Data mining. Information retrieval. Social networks analysis.

Featured Website