Friday, September 26, 2014

Ajax form in MVC

Ajax.BeginForm   It performed the Ajax request.  Example using Ajax.BeginForm  is gvien below

Model:

public class EmployeeModel
{
    [Required]
    public string Name { getset; }
      [Required]
    public string City { getset; }
}

Controller:

       public ActionResult Index()
    {
        return View(new EmployeeModel());
    }
[HttpPost]
    public ActionResult Index(EmployeeModel model)
    {
         //save Data
        return Content("Thanks""text/html");
    }

View

Now to handle the request we add "UnobtrusiveJavaScriptEnabled" as a key in the web.config file under the "<appSettings>" section.

<appSettings>
    <
add key="webpages:Enabled" value="false" />
    <
add key="ClientValidationEnabled" value="true"/>
    <
add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</
appSettings>

@model  WebApplication5.Models.EmployeeModel

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/index.js")" type="text/javascript"></script>

<div id="result"></div>

@using (Ajax.BeginForm("PerformAction",
    new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
    @Html.EditorFor(x => x.Name)
    @Html.ValidationMessageFor(x => x.Name)
   
     @Html.EditorFor(x => x.City)
    @Html.ValidationMessageFor(x => x.City)
    <input type="submit" value="OK" />
}
<div id="response"> </div>
<script>

    function OnSuccess(response) {
        $("#response").html(response)
      
    }

    function OnFailure(response) {
        alert("error occur");
    }

</script>

No comments:

Post a Comment

http://blogsiteslist.com