简体   繁体   中英

Form submit returns response with contentType as application/json instead of text/html

I submit a form using jQuery with post method.

<form action="/controller/ActionName" id="formDetail" method="post" onsubmit="" target="_top">
    <input name="name" type="hidden" value="name123" />
</form>


/* jQuery code to submit form*/

$("#formDetail").submit();

Controller

public ViewResult ActionName(string name)
{
    // rest of code 
    return View("viewName", model);
}

The controller action returns view properly. But browser receives response with contentType as application/json and complete html markup in response is displayed on screen(actually wrapped inside a <pre> tag)

If jQuery code is replaced with below it works perfectly, response has contentType as text/html and proper html page is displayed.

window.location.href = '/controller/action?name=name';

Tried setting Response.ContentType = "text/html" as suggested in similar questions on SO but no luck.

Found out what is happening, but still not sure why.

When form is submitted, it hits the action controller/ActionName and returns html view. This view contains @Html.Action("anotherAction") . Now this anotherAction has two variants - HttpGet and HttpPost. Since I am doing a form submit with POST method, @Html.Action("anotherAction") is hitting the HttpPost variant which is returning a JSON response(so content type Application/json ).

So the content type for whole response is overridden by a final call in the process to anotherAction which is returning JSON. But I am still not able to find why this happens.

You can fix this behavior by changing form's method to get . But in my case that POST exist for a reason and I had to change multiple things to make the original form submit work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM