Search code examples
c#ajaxjsonmonojsonresult

Returning JSONResult without switching views


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?


Solution

  • For your first question, check the following:

    1) Make sure you have Microsoft.jQuery.Unobtrusive.Ajax included and referenced

    2) OnSuccess = "MySuccessMethod()" should be OnSuccess = "MySuccessMethod" (where MySuccessMethod is a JavaScript method, not a C# one)

    For your second question, you could have your method return ActionResult instead of JsonResult (see here for more information). JsonResult is a type of ActionResult, which means that updating your action to return ActionResult will allow your method to return multiple types of ActionResult depending on the scenario:

    [HttpPost]
    public ActionResult SomeThing(int randomParam)
    {
        if (randomParam == 0)
        { 
            return Json("Zero!"); 
        }
        else if (randomParam == 1)
        {
            return View("Not zero!");
        }
        else
        {
            return HttpNotFound("Error: I can only find zeroes and ones");
        }
    }
    

    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 of ActionResult) 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 - use ActionResult when your action returns more than one type of result.