Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Submit a form using Ajax instead of Normal Post

5.00/5 (1 vote)
26 Nov 2011CPOL 8.7K  
For ASP.NET MVC, HERE! is a much cooler approach:Basically, we use Ajax.ActionLink like this:The controller takes care of both the possibilities (Normal Post...
For ASP.NET MVC, HERE! is a much cooler approach:

Basically, we use Ajax.ActionLink like this:

HTML
<![CDATA[<%= Ajax.ActionLink(item.Name, "Index", new { id = item.Id }, new AjaxOptions { UpdateTargetId = "divContactList"})%>


The controller takes care of both the possibilities (Normal Post as well as Ajax post request):

C#
public ActionResult Index(int? id)
{
    // Get selected group
    var selectedGroup = _service.GetGroup(id);
    if (selectedGroup == null)
        return RedirectToAction("Index", "Group");

    // Normal Request
    if (!Request.IsAjaxRequest())
    {
        var model = new IndexModel
        {
            Groups = _service.ListGroups(),
            SelectedGroup = selectedGroup
        };
        return View("Index", model);
    }

    // Ajax Request
    return PartialView("ContactList", selectedGroup);
}


Of course, we need the three script references:

HTML
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)