Home
Manage Your Code
Snippet: MVC Ajax Post ActionLink (ASP.NET)
Title: MVC Ajax Post ActionLink Language: ASP.NET
Description: Call an actionresult in Async using Ajax.Action then return a json data, then create a JS method that consumes the Json and display it. Views: 1032
Author: John bonsol Date Added: 6/19/2012
Copy Code  
Razor Part
@Ajax.ActionLink("View", -> This is the name that displays on the link
                 "Index",-> This is the Action Name
                 new { ValId = item.MPID },-> This is the routeArgument/parameter
                 new AjaxOptions { HttpMethod = "POST", 
                                   OnSuccess = "displayContent" })

----->this actionlink is use to call the actionresult in the controller

Csharp / Controller Part
public ActionResult Index(string ValId)
    List<object> mpcList = new List<object>();
    //do something like populate the list
return Json(mpcList, JsonRequestBehavior.AllowGet);

-----> After calling the Actionresult it returns a json data, 
       after the whole actionresult is finish, 
       an event is triggered "OnSuccess" to call a method to consume
       the json data and display it.

Javascript Part
<script type="text/javascript">
    function displayContent(obj) {
            //obj -> is the returned json format data
            //this example is a table/list structured data
            for (var i = 0; i < obj.length; i++) {
                //do something
            }
        }

        $('#ajaxresult').replaceWith($tbl);
    }
</script>