using Ajax.BeginForm() in Asp.net mvc

Posting Data using Ajax.BeginForm()

In my previous article i show you how we can use Model binding in asp.net and post data back to server. Today i will show you same technique with Ajax.BeginForm(). For this purpose we use built in client libraries which can be downloaded via nu-get.

Get Started

First open your package manager console from Tools->Library package manager->package manager console and write following command
Install-Package Microsoft.jQuery.Unobtrusive.Ajax
Now include fallowing file reference in your main layout file under views->shared folder.

    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

Web.config changes

open your web.config file and add these lines under configuration tag.

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

Controller Code

Now this is time to connect with database. you can use any database for testing purpose. here i create a test product table in my database and connect that database with my application using entity-framework-database-first-approach. you can learn it in in this article. Now add a new controller name it AjaxFormController and add its index View.

Index view code

@model MultipleFileUploads.Database.ProductTable
@{
    ViewBag.Title = "Index";
}
@using (Ajax.BeginForm("RegisterAuthor","AjaxForm",FormMethod.Post, new AjaxOptions{UpdateTargetId="ShowStatus"}))
{
    @Html.AntiForgeryToken()

    <label>Enter Product Name</label>
    @Html.TextBoxFor(model=>model.product_name)
    <label>Enter Product Description</label>
    @Html.TextBoxFor(model=>model.product_description)
    <button>Save Product</button>
    
}
<div id="ShowStatus">

</div>

I create this view strongly type. As you can see there is Ajax.BeginForm() which contain our Action name which take care of our insertion, second parameter is our controller name, third is form method which is post in this case,and fourth is which div updated after insertion.

Controller Code

Now we define our RegisterAuthor ActionResult which save records in database

public ActionResult RegisterAuthor(ProductTable NewProduct)
        {
            if (ModelState.IsValid)
            {
                using (pubsEntities dbcontext=new pubsEntities())
                {
                    dbcontext.ProductTables.Add(NewProduct);
                    if (dbcontext.SaveChanges() > 0)
                    {
                        return Content("New Author Add Successfully");
                    }
                    else
                    {
                        return Content("Please try again");
                    }
                }
            }
            else
            {
                return View(NewProduct);
            }
        }

Result

Now run you application and go to your define controller and its index method in my case it is /AjaxForm/Index. Fill the form and hit Save product button. Records will be save to database and its response render in given div without page post back to server. in this process your page URL remain constant.