Saturday, January 8, 2011

Microsoft AJAX returning JSON needs JavaScriptSerializer for deserialization

Microsoft AJAX  require JavaScriptSerializer to deserialize return object into JSON object. Use get-data() to extract object prior to deserialization.
Consider the code snip 
View
  <%using (Ajax.BeginForm("GetJSONGreeting", new AjaxOptions
                                                  {
                                                      OnComplete = "onComplete"
                                                  }))

...

 <script type="text/javascript">
           function onComplete(data) {
               var obj = Sys.Serialization.JavaScriptSerializer.deserialize(data.get_data());
               alert(obj.Message);
           }
    </script>
Controller
 public JsonResult GetJSONGreeting(string name)
        { 
            return Json( new {Message = string.Format("Hello {0} from JSON", name)});
        }

1 comment:

  1. Good question has been posted regarding who JSON response generated by AJAX Form can be handled here
    How to post ASP.NET MVC Ajax form using JavaScript rather than submit button
    http://stackoverflow.com/questions/1305601/how-to-post-asp-net-mvc-ajax-form-using-javascript-rather-than-submit-button

    ReplyDelete