Submit form using AJAX in Asp.Net mvc 4

Here goes the complete example –

Lets create a simple model –

public class Details
{
    public string Name { get; set; }
    public string Email { get; set; }
}

Now lets create couple of Actions to make GET and POST requests using AJAX BEGINFORM

    static List<Details> details = new List<Details>(); 
    public ActionResult GetMe()
    {
        return View();
    }

    public ActionResult SaveData(Details d)
    {
        details.Add(d);
        return Json(details.Count, JsonRequestBehavior.AllowGet);
    }

Then lets create a simple view which will host Ajax.BeginForm() –

@model RamiSamples.Controllers.Details

@{
    ViewBag.Title = "Ajax";
}

<h2>Ajax</h2>
<script src="https://stackoverflow.com/questions/26191774/~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

@using (Ajax.BeginForm("SaveData", new AjaxOptions()
{
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "dane"
}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Details</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div id="dane">
    Number of Details : 
</div>

Now when the page gets rendered –

enter image description here

Now when you enter data and click on create button –

enter image description here

And then the page will automatically updated with the number of additions as shown below –

enter image description here

Leave a Comment