Search code examples
c#ajaxmodel-view-controllerjsonresponse

Can I add a json response when returning an MVC view with model?


Is there a way to add a JSON Result that would be consumed by the OnSuccess or OnFailure options of an AJAX.BeginForm when the controller is using the return View(model) syntax?

Everything is pretty standard C# / MVC. The Ajax.BeginForm would look like this

@using (Ajax.BeginForm("AnyAction", "Home", null,
    new AjaxOptions
    {
        HttpMethod = "Post",
        OnBegin = "OnBegin",
        OnFailure = "OnFailure(xhr, status)",
        OnSuccess = "OnSuccess(xhr, status)"
    },
    new { id = "myform" }))

The OnSuccess and OnFailure scripts are defined like this

    function OnSuccess(xhr, status) {
        console.log("OnSuccess");
    }
    function OnFailure(xhr, status) {
        console.log("OnFailure");       
    }

The controller returns like this

    HttpContext.Response.StatusCode = (int)HttpStatusCode.NotAcceptable;
    return View(model);

I can inject the HTTPStatusCode, either OK or Not OK, into the HTTPContext.Response and that will trigger the OnSuccess or OnFailure javascript functions. From that I know that I can manipulate the response stream but is there anyway to add a JSON response to the HTTPContext.Response such that the OnSuccess or OnFailure can consume it.

How can I pass this, while using the return View(model) syntax, to the OnSuccess function?

dynamic jsonMessage;
jsonMessage = new { param1 = "ModelState", param2 ="Error", param3 = "Error Message" };

Some quick notes:

This is not a requirement, just a question.

I am already using the Return JSON(jsonMessage, JsonRequestBehavior.AllowGet) elsewhere in my project, don't need help with that.


Solution

  • Since your JSON is small, you could add your JSON string as a response header using

    HttpContext.Response.AddHeader("json", "json_string");.

    It can then be accessed from the header value in OnSuccess/Failure method.