【问题标题】:Form submit returns response with contentType as application/json instead of text/html表单提交返回内容类型为 application/json 而不是 text/html 的响应
【发布时间】:2020-09-06 17:03:13
【问题描述】:

我使用带有 post 方法的 jQuery 提交表单。

<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();

控制器

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

控制器动作正确返回视图。但是浏览器接收到 contentType 为 application/json 的响应,并且完整的 html 标记作为响应显示在屏幕上(实际上包裹在 &lt;pre&gt; 标记内)

如果将 jQuery 代码替换为下面的代码,它可以正常工作,响应的 contentType 为 text/html,并显示正确的 html 页面。

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

尝试设置Response.ContentType = "text/html",如关于 SO 的类似问题中所建议的那样,但没有运气。

【问题讨论】:

    标签: javascript c# jquery asp.net-mvc forms


    【解决方案1】:

    发现发生了什么,但仍然不确定原因。

    当表单提交时,它会点击动作controller/ActionName 并返回html 视图。此视图包含@Html.Action("anotherAction")。现在这个anotherAction 有两个变体——HttpGet 和HttpPost。由于我正在使用 POST 方法提交表单,@Html.Action("anotherAction") 正在点击返回 JSON 响应的HttpPost 变体(因此内容类型为Application/json)。

    因此,整个响应的内容类型被过程中对返回 JSON 的 anotherAction 的最终调用覆盖。但我仍然无法找到为什么会发生这种情况。

    您可以通过将表单的方法更改为get 来解决此问题。但就我而言,POST 的存在是有原因的,我必须更改多项内容才能使原始表单提交工作。

    【讨论】:

      猜你喜欢
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      • 2016-03-10
      相关资源
      最近更新 更多