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.Ajaxincluded and referenced2)
OnSuccess = "MySuccessMethod()"should beOnSuccess = "MySuccessMethod"(whereMySuccessMethodis aJavaScriptmethod, not aC#one)For your second question, you could have your method return
ActionResultinstead ofJsonResult(see here for more information).JsonResultis a type ofActionResult, which means that updating your action to returnActionResultwill allow your method to return multiple types ofActionResultdepending 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,
JsonResultinstead 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 - useActionResultwhen your action returns more than one type of result.