Ajax BeginForm Explained

This example is very simple and can be found here on the website, you can try this one : Ajax fun
Ensure that "jquery.unobtrusive-ajax.js" is downoaded to the project and implemented. So that they represented in the following order:
<script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
Start by creating two controller methods as here. (notice that they return JSON strings...)
[HttpPost] public ActionResult AjaxPost1(string Name) { return Json("Good name you got there, "+ Name ); } [HttpPost] public ActionResult AjaxPost2(string Occupation) { return Json("Congratulation with your job as " + Occupation); }
Notice the names of the two methods. Add following code to the respective cshtml file:
@using (Ajax.BeginForm("AjaxPost1", "AjaxFun", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnFailure" })) { @Html.Label("Enter Your Name") <br/> @Html.TextBox("Name", null, new { @class = "form-control" }) <br/> <button id="btnSubmit" type="submit" class="btn btn-primary">Submit</button> } <div id="div1"> </div> < br /> @using (Ajax.BeginForm("AjaxPost2", "AjaxFun", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess1", OnFailure = "OnFailure" })) { @Html.Label("Enter Your occupation") <br/> @Html.TextBox("Occupation", null, new { @class = "form-control" }) <br/> <button id="btnSubmit" type="submit" class="btn btn-primary">Submit</button> } <div id="div2"> </div> <br />
As you can see there are two AJAX beginform on the page referring to the method names in the controller. Notice the Controller name, "Ajaxfun" and the AjaxOptions events, "Onsuccess" and "Onfailure". We only need to create the return events in the cshtml file;
function OnSuccess(data) { $("#div1").html(data); } function OnSuccess1(data) { $("#div2").html(data); } function OnFailure(data) { alert(data); }