I want to return a JSON result. To do this I have a controller method as follows that is called from a Ajax.BeginForm
on the View:
@using (Ajax.BeginForm("Update", new AjaxOptions { OnSuccess = "MySuccessMethod()" }))
{
<!-- some form stuff -->
<input type="submit" value="Submit"/>
}
This is the controller that handles it:
[HttpPost]
public JsonResult Update(FormCollection fc)
{
// Process form stuff
return Json (new {success = true });
}
What I want is to process the success response with MySuccessMethod
. What I see is that the view on submit goes to the correct controller method above, which then redirects the page to the URL /Home/Update
with the following string in the screen:
{"success": true }
Not sure if it is relevant but I am using Mono.
How can I make the framework not switch pages to /Home/Update
nor display the JSON string on the view and just process the JSON in the back?
For your first question, check the following:
1) Make sure you have
Microsoft.jQuery.Unobtrusive.Ajax
included and referenced2)
OnSuccess = "MySuccessMethod()"
should beOnSuccess = "MySuccessMethod"
(whereMySuccessMethod
is aJavaScript
method, not aC#
one)For your second question, you could have your method return
ActionResult
instead ofJsonResult
(see here for more information).JsonResult
is a type ofActionResult
, which means that updating your action to returnActionResult
will allow your method to return multiple types ofActionResult
depending on the scenario:As a general rule of thumb (although sometimes rules are meant to be broken), having your action return one type (like your example,
JsonResult
instead ofActionResult
) makes your action less error-prone as, for example, Visual Studio will let you know if you accidentally try to return another type of result - useActionResult
when your action returns more than one type of result.