65.9K
CodeProject is changing. Read more.
Home

Submit a form using Ajax instead of Normal Post

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (2 votes)

Nov 25, 2011

CPOL
viewsIcon

8711

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:
<![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):
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:
<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>