views:

9268

answers:

4

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.

+8  A: 

Try this:

var json_data = content.get_response().get_object();

this will give you result in JSON format and you can use json_data[0] to get the first record

Kobi
OK, this worked. It still seems convoluted however. I'm not sure why they just don't return the data directly.
Brian Vallelunga
So what is get_data() supposed to do then?
Schneider
+5  A: 

In response to the comment by Brian, the reason they "just don't return the data directly" is because the object form is not the default form of data being returned via HTTP. When you make an http call, you get a string back. The fact is that in order to turn it into an object, you must take an extra step to evaluate it using the eval function.

Joel Martinez
A: 

try using the below code.

function onTestComplete(content) { var result = eval( '(' + content.get_data() + ')' ); alert(result.UppercaseName); }
Russel
A: 

Make 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.

var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
Michael Callahan