Stefan Stefan - 5 months ago 28
Ajax Question

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

I have got this simple form:

@using (Ajax.BeginForm("CreateProductFromAjaxForm","Product" ,
null,
new AjaxOptions() { HttpMethod = "post", OnSuccess = "getresult" },
null))
{
@Html.EditorFor(m => m)
<hr />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-info" value="Next" />
</div>
</div>
}


And, for testing, a simple controller:

[HttpPost]
public JsonResult CreateProductFromAjaxForm(CreateProductModel model)
{
if (!ModelState.IsValid)
{
return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = "error" }
};
}

//add to database

return new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = "success"}
};
}


I have added these to the Web.Config:

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />


and these to my script bundle:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js"
));


After clicking the "Submit" button, the resulting page just shows:

{"result":"success"}


I would expect that I could handle the result in the
OnSuccess="getresult"
handler, but it doesn't seem to work.

Basically I am using the
Ajax.BeginForm
mainly for the clientside validation.

Can you tell me whats wrong?

UPDATE: I added the
HttpMethod = "post"
to the AjaxOptions.

UPDATE: The
getresult
, is defined above the
Ajax.BeginForm
like this:

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

Lin Lin
Answer

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

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