3

I have an ajax form that saves a object in the database then return a Message like this:

return Json(new {Message = "Message!"},
                            JsonRequestBehavior.AllowGet);

We are ok here, but I don't know HOW I'll get this result in the view to display in a jQuery modal. My ajax form is like the following and I want to get the result on the OnSuccess method:

<%using (Ajax.BeginForm("Form", "Controller", new AjaxOptions() {  OnSuccess = "MethodThatIWantToGetTheJson" }))%>

Any ideas?

moribvndvs
  • 42,191
  • 11
  • 135
  • 149
Diego Correa
  • 767
  • 2
  • 9
  • 22

2 Answers2

5

Try this (taken from How to use Ajax.BeginForm MVC helper with JSON result?):

<%using (Ajax.BeginForm("Form", "Controller", new AjaxOptions() { OnComplete = "MethodThatIWantToGetTheJson" }))

<script type='text/javascript'>
    function MethodThatIWantToGetTheJson(content) {
        alert(content.get_response().get_object());
    }
</script>
Community
  • 1
  • 1
LukLed
  • 31,452
  • 17
  • 82
  • 107
2

I'll use a jQuery example, because that's how I normally request anything using ASP.NET MVC. If we set up the ajax request, we get the response back as json.

$.ajax({
   url: 'Controller\Action\',
   type: 'POST',
   dataType: 'json'
   success: function(data, status)
   {
        // data will be your json result
        alert(data.Message);
   }
});

You could then just put that into some kind of jQuery logic like so:

var message = $('<span/>');
message.html(data.Message);
message.dialog();
Tejs
  • 40,736
  • 10
  • 68
  • 86