Can I add a json response when returning an MVC view with model?ASP.NET MVC controller actions that return JSON or partial htmlHow can I return the current action in an ASP.NET MVC view?In MVC, how do I return a string result?Why does Google prepend while(1); to their JSON responses?How should a model be structured in MVC?How do I return the response from an asynchronous call?Asp.Net MVC and Partial Views and Mixing Ajax.BeginForm and Html.BeginFormHow to call success callback function of knockout model from AjaxForm in mvcASP.NET MVC - ValidationSummary with MVC and AJAX callsWhy won't Ajax.BeginForm replace div?

German equivalent to "going down the rabbit hole"

Is "prohibition against," a double negative?

Could a complex system of reaction wheels be used to propel a spacecraft?

Understanding data transmission rates over copper wire

Don't look at what I did there

What checks exist against overuse of presidential pardons in the USA?

What's the origin of the concept of alternate dimensions/realities?

In what language did Túrin converse with Mím?

Storing milk for long periods of time

Magnetic thread storage?

Calculate Landau's function

Why do presidential pardons exist in a country having a clear separation of powers?

Resources to learn about firearms?

Why haven't the British protested Brexit as ardently like Hong Kongers protest?

Where should I draw the line on follow up questions from previous employer

What was Captain Marvel supposed to do once she reached her destination?

Why doesn't Starship have four landing legs?

Is this homebrew "Faerie Fire Grenade" unbalanced?

Break down the phrase "shitsurei shinakereba naranaindesu"

Can authors email you PDFs of their textbook for free?

Connecting points from separate Tikz figures

Cheap oscilloscope showing 16 MHz square wave

Why don't 3D printer heads use ceramic inner walls?

Sum and average calculator



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


ASP.NET MVC controller actions that return JSON or partial htmlHow can I return the current action in an ASP.NET MVC view?In MVC, how do I return a string result?Why does Google prepend while(1); to their JSON responses?How should a model be structured in MVC?How do I return the response from an asynchronous call?Asp.Net MVC and Partial Views and Mixing Ajax.BeginForm and Html.BeginFormHow to call success callback function of knockout model from AjaxForm in mvcASP.NET MVC - ValidationSummary with MVC and AJAX callsWhy won't Ajax.BeginForm replace div?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















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.










share|improve this question
























  • You could add your JSON string as a response header using HttpContext.Response.AddHeader("json", "json_string");. You could then access the header value in your OnSuccess/Failure method. It can seem like a hack because response headers aren't meant to carry data. How big is your JSON?

    – Saharsh
    Mar 28 at 1:12











  • The JSON is quite small, only a couple of flags. I was thinking it would be something in the output stream but the header makes more sense. I will verify this early tomorrow and give what credit I can to a comment.

    – vscoder
    Mar 28 at 4:29











  • I'll add it to the answer since a header solution would be acceptable. Alternatively you could have put it into a Model property, that could then be bound with a data-* attribute of a hidden field in your CSHTML. It would need a few extra lines of code in your OnSuccess to get the JSON out from that data-* attribute, but that could also work for larger jsons.

    – Saharsh
    Mar 28 at 13:02


















1















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.










share|improve this question
























  • You could add your JSON string as a response header using HttpContext.Response.AddHeader("json", "json_string");. You could then access the header value in your OnSuccess/Failure method. It can seem like a hack because response headers aren't meant to carry data. How big is your JSON?

    – Saharsh
    Mar 28 at 1:12











  • The JSON is quite small, only a couple of flags. I was thinking it would be something in the output stream but the header makes more sense. I will verify this early tomorrow and give what credit I can to a comment.

    – vscoder
    Mar 28 at 4:29











  • I'll add it to the answer since a header solution would be acceptable. Alternatively you could have put it into a Model property, that could then be bound with a data-* attribute of a hidden field in your CSHTML. It would need a few extra lines of code in your OnSuccess to get the JSON out from that data-* attribute, but that could also work for larger jsons.

    – Saharsh
    Mar 28 at 13:02














1












1








1


2






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.










share|improve this question














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.







c# ajax model-view-controller jsonresponse






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 23:04









vscodervscoder

1729 bronze badges




1729 bronze badges















  • You could add your JSON string as a response header using HttpContext.Response.AddHeader("json", "json_string");. You could then access the header value in your OnSuccess/Failure method. It can seem like a hack because response headers aren't meant to carry data. How big is your JSON?

    – Saharsh
    Mar 28 at 1:12











  • The JSON is quite small, only a couple of flags. I was thinking it would be something in the output stream but the header makes more sense. I will verify this early tomorrow and give what credit I can to a comment.

    – vscoder
    Mar 28 at 4:29











  • I'll add it to the answer since a header solution would be acceptable. Alternatively you could have put it into a Model property, that could then be bound with a data-* attribute of a hidden field in your CSHTML. It would need a few extra lines of code in your OnSuccess to get the JSON out from that data-* attribute, but that could also work for larger jsons.

    – Saharsh
    Mar 28 at 13:02


















  • You could add your JSON string as a response header using HttpContext.Response.AddHeader("json", "json_string");. You could then access the header value in your OnSuccess/Failure method. It can seem like a hack because response headers aren't meant to carry data. How big is your JSON?

    – Saharsh
    Mar 28 at 1:12











  • The JSON is quite small, only a couple of flags. I was thinking it would be something in the output stream but the header makes more sense. I will verify this early tomorrow and give what credit I can to a comment.

    – vscoder
    Mar 28 at 4:29











  • I'll add it to the answer since a header solution would be acceptable. Alternatively you could have put it into a Model property, that could then be bound with a data-* attribute of a hidden field in your CSHTML. It would need a few extra lines of code in your OnSuccess to get the JSON out from that data-* attribute, but that could also work for larger jsons.

    – Saharsh
    Mar 28 at 13:02

















You could add your JSON string as a response header using HttpContext.Response.AddHeader("json", "json_string");. You could then access the header value in your OnSuccess/Failure method. It can seem like a hack because response headers aren't meant to carry data. How big is your JSON?

– Saharsh
Mar 28 at 1:12





You could add your JSON string as a response header using HttpContext.Response.AddHeader("json", "json_string");. You could then access the header value in your OnSuccess/Failure method. It can seem like a hack because response headers aren't meant to carry data. How big is your JSON?

– Saharsh
Mar 28 at 1:12













The JSON is quite small, only a couple of flags. I was thinking it would be something in the output stream but the header makes more sense. I will verify this early tomorrow and give what credit I can to a comment.

– vscoder
Mar 28 at 4:29





The JSON is quite small, only a couple of flags. I was thinking it would be something in the output stream but the header makes more sense. I will verify this early tomorrow and give what credit I can to a comment.

– vscoder
Mar 28 at 4:29













I'll add it to the answer since a header solution would be acceptable. Alternatively you could have put it into a Model property, that could then be bound with a data-* attribute of a hidden field in your CSHTML. It would need a few extra lines of code in your OnSuccess to get the JSON out from that data-* attribute, but that could also work for larger jsons.

– Saharsh
Mar 28 at 13:02






I'll add it to the answer since a header solution would be acceptable. Alternatively you could have put it into a Model property, that could then be bound with a data-* attribute of a hidden field in your CSHTML. It would need a few extra lines of code in your OnSuccess to get the JSON out from that data-* attribute, but that could also work for larger jsons.

– Saharsh
Mar 28 at 13:02













2 Answers
2






active

oldest

votes


















1















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.






share|improve this answer

























  • Saharsh, I gave you credit for pointing me in the right direction but I wanted to provide a more complete answer, since there were several additional steps involved and anyone that finds this post should have a complete answer.

    – vscoder
    Mar 28 at 16:43


















1















I wanted to follow up with the my final solution. First we need to adjust the OnSuccess definition of the Ajax.BeginForm property to look like this. I tried several variations of this but this exact code is the only one that worked.



@using (Ajax.BeginForm("AddUserRole", "AppRoles", null,
new AjaxOptions

HttpMethod = "Post",
OnBegin = "OnBegin",
OnFailure = "OnFailure(xhr, status)",
OnSuccess = "OnSuccess(data, status, xhr)"
,
new id = "myform" ))


Next the javascript for the OnSuccess looks like this. A few things to note; first the controller, shown farther down, can return either a JsonResult or a View / Model. The OnSuccess function will be fired regardless of which is returned as long as the HttpResponseStatus is OK. If the controller returns a View/Model, the data parm will contain the entire rendered view and the json I want will be in the XHR parameter. To work with the json response it must be extracted using the getResponseHeader and then serialized to JSON. After that we can work with it as a regular old JSON object.



function OnSuccess(data, status, xhr) 
console.log("OnSuccess");
// this is for capturing from the Response header WHEN the controller returns a view
var srchMessage = xhr.getResponseHeader("srchMessage")
if (srchMessage != null)
var srchJson = JSON.parse(srchMessage);
console.log("srchMessage:param1" + srchJson.param1);
return;

// this is for capturing the json WHEN the controller returns a JsonResult
if (xhr.responseJSON != null)
console.log("xhr.responseJSON.param1" + xhr.responseJSON.param1);




The MVC controller can return either a 'short' JsonResult or the complete view, looks kinda like this



public ActionResult AjaxTest(AppModel model)

if (model.status == "ReturnView")

jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonMessage);
HttpContext.Response.AddHeader("srchMessage", jsonString);
HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
return View(model);


if (model.status == "ReturnJSON")

jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
return Json(jsonMessage, JsonRequestBehavior.AllowGet);




I'm not sure why I wanted to do this, I should have separate controllers for the different actions, but this is how it can be done if you wanted to do it.






share|improve this answer



























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387807%2fcan-i-add-a-json-response-when-returning-an-mvc-view-with-model%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1















    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.






    share|improve this answer

























    • Saharsh, I gave you credit for pointing me in the right direction but I wanted to provide a more complete answer, since there were several additional steps involved and anyone that finds this post should have a complete answer.

      – vscoder
      Mar 28 at 16:43















    1















    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.






    share|improve this answer

























    • Saharsh, I gave you credit for pointing me in the right direction but I wanted to provide a more complete answer, since there were several additional steps involved and anyone that finds this post should have a complete answer.

      – vscoder
      Mar 28 at 16:43













    1














    1










    1









    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.






    share|improve this answer













    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.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 28 at 13:03









    SaharshSaharsh

    6666 silver badges17 bronze badges




    6666 silver badges17 bronze badges















    • Saharsh, I gave you credit for pointing me in the right direction but I wanted to provide a more complete answer, since there were several additional steps involved and anyone that finds this post should have a complete answer.

      – vscoder
      Mar 28 at 16:43

















    • Saharsh, I gave you credit for pointing me in the right direction but I wanted to provide a more complete answer, since there were several additional steps involved and anyone that finds this post should have a complete answer.

      – vscoder
      Mar 28 at 16:43
















    Saharsh, I gave you credit for pointing me in the right direction but I wanted to provide a more complete answer, since there were several additional steps involved and anyone that finds this post should have a complete answer.

    – vscoder
    Mar 28 at 16:43





    Saharsh, I gave you credit for pointing me in the right direction but I wanted to provide a more complete answer, since there were several additional steps involved and anyone that finds this post should have a complete answer.

    – vscoder
    Mar 28 at 16:43













    1















    I wanted to follow up with the my final solution. First we need to adjust the OnSuccess definition of the Ajax.BeginForm property to look like this. I tried several variations of this but this exact code is the only one that worked.



    @using (Ajax.BeginForm("AddUserRole", "AppRoles", null,
    new AjaxOptions

    HttpMethod = "Post",
    OnBegin = "OnBegin",
    OnFailure = "OnFailure(xhr, status)",
    OnSuccess = "OnSuccess(data, status, xhr)"
    ,
    new id = "myform" ))


    Next the javascript for the OnSuccess looks like this. A few things to note; first the controller, shown farther down, can return either a JsonResult or a View / Model. The OnSuccess function will be fired regardless of which is returned as long as the HttpResponseStatus is OK. If the controller returns a View/Model, the data parm will contain the entire rendered view and the json I want will be in the XHR parameter. To work with the json response it must be extracted using the getResponseHeader and then serialized to JSON. After that we can work with it as a regular old JSON object.



    function OnSuccess(data, status, xhr) 
    console.log("OnSuccess");
    // this is for capturing from the Response header WHEN the controller returns a view
    var srchMessage = xhr.getResponseHeader("srchMessage")
    if (srchMessage != null)
    var srchJson = JSON.parse(srchMessage);
    console.log("srchMessage:param1" + srchJson.param1);
    return;

    // this is for capturing the json WHEN the controller returns a JsonResult
    if (xhr.responseJSON != null)
    console.log("xhr.responseJSON.param1" + xhr.responseJSON.param1);




    The MVC controller can return either a 'short' JsonResult or the complete view, looks kinda like this



    public ActionResult AjaxTest(AppModel model)

    if (model.status == "ReturnView")

    jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
    string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonMessage);
    HttpContext.Response.AddHeader("srchMessage", jsonString);
    HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
    return View(model);


    if (model.status == "ReturnJSON")

    jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
    HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
    return Json(jsonMessage, JsonRequestBehavior.AllowGet);




    I'm not sure why I wanted to do this, I should have separate controllers for the different actions, but this is how it can be done if you wanted to do it.






    share|improve this answer





























      1















      I wanted to follow up with the my final solution. First we need to adjust the OnSuccess definition of the Ajax.BeginForm property to look like this. I tried several variations of this but this exact code is the only one that worked.



      @using (Ajax.BeginForm("AddUserRole", "AppRoles", null,
      new AjaxOptions

      HttpMethod = "Post",
      OnBegin = "OnBegin",
      OnFailure = "OnFailure(xhr, status)",
      OnSuccess = "OnSuccess(data, status, xhr)"
      ,
      new id = "myform" ))


      Next the javascript for the OnSuccess looks like this. A few things to note; first the controller, shown farther down, can return either a JsonResult or a View / Model. The OnSuccess function will be fired regardless of which is returned as long as the HttpResponseStatus is OK. If the controller returns a View/Model, the data parm will contain the entire rendered view and the json I want will be in the XHR parameter. To work with the json response it must be extracted using the getResponseHeader and then serialized to JSON. After that we can work with it as a regular old JSON object.



      function OnSuccess(data, status, xhr) 
      console.log("OnSuccess");
      // this is for capturing from the Response header WHEN the controller returns a view
      var srchMessage = xhr.getResponseHeader("srchMessage")
      if (srchMessage != null)
      var srchJson = JSON.parse(srchMessage);
      console.log("srchMessage:param1" + srchJson.param1);
      return;

      // this is for capturing the json WHEN the controller returns a JsonResult
      if (xhr.responseJSON != null)
      console.log("xhr.responseJSON.param1" + xhr.responseJSON.param1);




      The MVC controller can return either a 'short' JsonResult or the complete view, looks kinda like this



      public ActionResult AjaxTest(AppModel model)

      if (model.status == "ReturnView")

      jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
      string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonMessage);
      HttpContext.Response.AddHeader("srchMessage", jsonString);
      HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
      return View(model);


      if (model.status == "ReturnJSON")

      jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
      HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
      return Json(jsonMessage, JsonRequestBehavior.AllowGet);




      I'm not sure why I wanted to do this, I should have separate controllers for the different actions, but this is how it can be done if you wanted to do it.






      share|improve this answer



























        1














        1










        1









        I wanted to follow up with the my final solution. First we need to adjust the OnSuccess definition of the Ajax.BeginForm property to look like this. I tried several variations of this but this exact code is the only one that worked.



        @using (Ajax.BeginForm("AddUserRole", "AppRoles", null,
        new AjaxOptions

        HttpMethod = "Post",
        OnBegin = "OnBegin",
        OnFailure = "OnFailure(xhr, status)",
        OnSuccess = "OnSuccess(data, status, xhr)"
        ,
        new id = "myform" ))


        Next the javascript for the OnSuccess looks like this. A few things to note; first the controller, shown farther down, can return either a JsonResult or a View / Model. The OnSuccess function will be fired regardless of which is returned as long as the HttpResponseStatus is OK. If the controller returns a View/Model, the data parm will contain the entire rendered view and the json I want will be in the XHR parameter. To work with the json response it must be extracted using the getResponseHeader and then serialized to JSON. After that we can work with it as a regular old JSON object.



        function OnSuccess(data, status, xhr) 
        console.log("OnSuccess");
        // this is for capturing from the Response header WHEN the controller returns a view
        var srchMessage = xhr.getResponseHeader("srchMessage")
        if (srchMessage != null)
        var srchJson = JSON.parse(srchMessage);
        console.log("srchMessage:param1" + srchJson.param1);
        return;

        // this is for capturing the json WHEN the controller returns a JsonResult
        if (xhr.responseJSON != null)
        console.log("xhr.responseJSON.param1" + xhr.responseJSON.param1);




        The MVC controller can return either a 'short' JsonResult or the complete view, looks kinda like this



        public ActionResult AjaxTest(AppModel model)

        if (model.status == "ReturnView")

        jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
        string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonMessage);
        HttpContext.Response.AddHeader("srchMessage", jsonString);
        HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
        return View(model);


        if (model.status == "ReturnJSON")

        jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
        HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
        return Json(jsonMessage, JsonRequestBehavior.AllowGet);




        I'm not sure why I wanted to do this, I should have separate controllers for the different actions, but this is how it can be done if you wanted to do it.






        share|improve this answer













        I wanted to follow up with the my final solution. First we need to adjust the OnSuccess definition of the Ajax.BeginForm property to look like this. I tried several variations of this but this exact code is the only one that worked.



        @using (Ajax.BeginForm("AddUserRole", "AppRoles", null,
        new AjaxOptions

        HttpMethod = "Post",
        OnBegin = "OnBegin",
        OnFailure = "OnFailure(xhr, status)",
        OnSuccess = "OnSuccess(data, status, xhr)"
        ,
        new id = "myform" ))


        Next the javascript for the OnSuccess looks like this. A few things to note; first the controller, shown farther down, can return either a JsonResult or a View / Model. The OnSuccess function will be fired regardless of which is returned as long as the HttpResponseStatus is OK. If the controller returns a View/Model, the data parm will contain the entire rendered view and the json I want will be in the XHR parameter. To work with the json response it must be extracted using the getResponseHeader and then serialized to JSON. After that we can work with it as a regular old JSON object.



        function OnSuccess(data, status, xhr) 
        console.log("OnSuccess");
        // this is for capturing from the Response header WHEN the controller returns a view
        var srchMessage = xhr.getResponseHeader("srchMessage")
        if (srchMessage != null)
        var srchJson = JSON.parse(srchMessage);
        console.log("srchMessage:param1" + srchJson.param1);
        return;

        // this is for capturing the json WHEN the controller returns a JsonResult
        if (xhr.responseJSON != null)
        console.log("xhr.responseJSON.param1" + xhr.responseJSON.param1);




        The MVC controller can return either a 'short' JsonResult or the complete view, looks kinda like this



        public ActionResult AjaxTest(AppModel model)

        if (model.status == "ReturnView")

        jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
        string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonMessage);
        HttpContext.Response.AddHeader("srchMessage", jsonString);
        HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
        return View(model);


        if (model.status == "ReturnJSON")

        jsonMessage = new param1 = "param1", param2 = "param2", param3 = "param3" ;
        HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
        return Json(jsonMessage, JsonRequestBehavior.AllowGet);




        I'm not sure why I wanted to do this, I should have separate controllers for the different actions, but this is how it can be done if you wanted to do it.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 28 at 17:13









        vscodervscoder

        1729 bronze badges




        1729 bronze badges






























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387807%2fcan-i-add-a-json-response-when-returning-an-mvc-view-with-model%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현