I'm trying to use the ASP.NET MVC Ajax.BeginForm helper but don't want to use the existing content insertion options when the call completes. Instead, I want to use a custom JavaScript function as the callback.
This works, but the result I want should be returned as JSON. Unfortunately, the framework just treats the data as a string. Below is the client code. The server code simply returns a JsonResult with one field, UppercaseName.
<script type='text/javascript'>
function onTestComplete(content) {
var result = content.get_data();
alert(result.UppercaseName);
}
</script>
<% using (Ajax.BeginForm("JsonTest", new AjaxOptions() {OnComplete = "onTestComplete" })) { %>
<%= Html.TextBox("name") %><br />
<input type="submit" />
<%} %>
Instead of showing the uppercase result, it is instead showing undefined. content.get_data() seems to hold the JSON, but only in string form. How do I go about converting this to an object?
All of this seems a bit convoluted really. Is there a better way to get at the resulting content using Ajax.BeginForm? If it's this hard, I may skip Ajax.BeginForm entirely and just use the jQuery form library.
Try this:
this will give you result in JSON format and you can use
json_data[0]
to get the first recordMake sure you have included MicrosoftAjax.js and MicrosoftMvcAjax.js. Then use the following calls on the returned context to get a json object out of the return.
I use:
You can use
OnFailure
andOnSuccess
instead ofOnComplete
;OnSuccess
gives you the data as a proper JSON object. You can find the callback method signatures burried in~/Scripts/jquery.unobtrusive-ajax.min.js
which you should load on your page.In your
Ajax.BeginForm
:Script block:
These signatures match
success
anderror
callbacks in $.ajax(...), which might not be such a surprise after all.This was tested using asp.net-mvc-3 with jquery 1.6.3 and 1.7.2.
Try using the below code: