How can I return a JSON result to a Ajax.BeginForm How can I return a JSON result to a Ajax.BeginForm ajax ajax

How can I return a JSON result to a Ajax.BeginForm


you need to include jquery.unobtrusive-ajax.js file.

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


JsonResult is just a kind of ActionResult derived class that indicates that this action will return JSON instead of a view or something else.

For example:

 @using (Ajax.BeginForm("CreateProductFromAjaxForm","Product" , null,               new AjaxOptions() {  OnSuccess = "getresult" }, null))

This will generate a element which will send an AJAX request when submitted to the action. For this to work you need to include the following script to your page:

Now all that's left is to write this onSuccess javascript function and process the JSON results returned by the server:

<script type="text/javascript">var onSuccess = function(data) {    alert(data.result);};</script


in page

new AjaxOptions() {      OnSuccess = "getresult", }

in javascript

function getresult(data){   alert(data.x);}

in c#

[HttpPost]public ActionResult CreateProductFromAjaxForm(CreateProductModel model){    if (!ModelState.IsValid)    {        return Json("error", JsonRequestBehavior.AllowGet);    }   //add to database    return Json(model, JsonRequestBehavior.AllowGet);}