我在一个表单中有一些禁用的输入,我想将它们发送到服务器,但Chrome将它们从请求中排除。

在不添加隐藏字段的情况下,有什么解决办法吗?

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <!-- this does not appear in request -->
    <input type="textbox" name="Percentage" value="100" disabled="disabled" /> 

</form>

当前回答

简单的解决方法-只是使用隐藏字段作为选择,复选框和无线电占位符。

从这个代码到-

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <!-- this does not appear in request -->
    <input type="textbox" name="Percentage" value="100" disabled="disabled" /> 
    <select name="gender" disabled="disabled">
          <option value="male">Male</option>
          <option value="female" selected>Female</option>
    </select>

</form>

那个代码

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <input type="textbox" value="100" readonly /> 

    <input type="hidden" name="gender" value="female" />
    <select name="gender" disabled="disabled">
          <option value="male">Male</option>
          <option value="female" selected>Female</option>
    </select>
</form>

其他回答

use

<input type="textbox" name="" value="100" disabled/>

or

<input type="textbox" name="" value="100" readonly/>

如果你使用像PHP Laravel这样的框架,没有name属性的元素将读为unset

<input type="textbox" value="100" disabled/>

除了启用输入外,要从禁用输入中提交值,只需在提交表单时重新启用表单的所有输入。

<form onsubmit="this.querySelectorAll('input').forEach(i => i.disabled = false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

如果你喜欢jQuery:

<form onsubmit="$(this).find('input').prop('disabled', false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

ASP。NET MVC c# Razor,你像这样添加提交处理程序:

using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post,
    // Re-enable all input elements on submit so they are all posted, even if currently disabled.
    new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" } ))
{
    <!-- form content with input elements -->
}

除了Tom Blodget的响应,你可以简单地添加@HtmlBeginForm作为表单动作,就像这样:

 <form id="form" method="post" action="@Html.BeginForm("action", "controller", FormMethod.Post, new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" })"

我发现这样更容易。只读输入字段,然后设置它的样式,以便最终用户知道它是只读的。放置在这里的输入(例如来自AJAX)仍然可以提交,不需要额外的代码。

<input readonly style="color: Grey; opacity: 1; ">

带有disabled属性的元素不会被提交,或者您可以说它们的值没有被发布(参见HTML 5规范中关于构建表单数据集的步骤3下的第二个要点)。

也就是说,

<input type="textbox" name="Percentage" value="100" disabled="disabled" /> 

供参考,根据HTML 4规范中的17.12.1:

禁用控件无法接收焦点。 在选项卡导航中跳过禁用控件。 无法成功张贴已禁用的控件。

你可以使用readonly属性在你的情况下,通过这样做,你将能够发布你的字段的数据。

也就是说,

<input type="textbox" name="Percentage" value="100" readonly="readonly" />

供参考,根据HTML 4规范中的17.12.2:

只读元素接收焦点,但用户不能修改。 选项卡导航中包含只读元素。 只读元素被成功发布。