how ajax.beginform works in mvc ?

avnish
avnish
242 Points
11 Posts

Can we use Ajax.Beginform as update panel in mvc.

If not then please give me an example to when and why use Ajax.BeginForm

Views: 10485
Total Answered: 1
Total Marked As Answer: 1
Posted On: 02-Sep-2015 11:14

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4916 Points
27 Posts
         

Hi Avnish,

Ajax.Beginform is not same as update panel in webform technology.
Ajax.Beginform is submitted form asynchronously using Javascript. So it required, to load the script files for execution. Even though its a small performance compromise, the execution happens with out postback.
We can understand by following differences between Ajax.Beginform and Html.BeginForm:

Ajax.Beginform:

  • does not redirect the form even you do a RedirectAction().
  • performs save , update and any modification operations asynchronously.

Html.BeginForm:

  • redirects the form.
  • performs operations both Synchronously and Asynchronously (With some extra code and care).

Ajax.Beginform Example:

 1. Add Controller as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{  
public class Default1Controller : Controller
{
 
//
 
// GET: /Default1/
 
public ActionResult Index()
return View();
}
 
public ActionResult AjaxForm()
return View();
}
[HttpPost] 
public ActionResult AjaxForm(FormCollection collection, string button)
return Content("Textbox value :"+ collection.GetValue("textajax").AttemptedValue + "<= Ajax updated successfully..");
}
}
 
}

 

2. _layout view as:

<!DOCTYPE html>
<html>
<head>
 
<meta charset="utf-8" />
 
<meta name="viewport" content="width=device-width" />
 
<title>@ViewBag.Title</title>
 
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
 
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
@RenderBody()
</body>
</html>

3. AjaxForm View as: 

@{
ViewBag.Title ="AjaxForm";
Layout ="~/Views/Shared/_Layout.cshtml";
}
<h2>AjaxForm</h2>
@using (Ajax.BeginForm("AjaxForm", "Default1", new AjaxOptions { LoadingElementId = "Loadingdiv", UpdateTargetId = "updatetable", HttpMethod = "post" }))
<div id="Loadingdiv" style="display:none;">loading...</div>
 
<input name="textajax" />
 
<button>submit ajax</button>
}
<table id="updatetable"></table>
Posted On: 03-Sep-2015 04:42
See more detail here: http://www.niceonecode.com/Blog/DotNet/MVC/AJAX-Helpers-(Ajax_BeginForm(),-Ajax_ActionLink())-in-ASP_NET-MVC/13
 - Brian  09-Jan-2018 23:49
 Log In to Chat