我在一个表单中有一些禁用的输入,我想将它们发送到服务器,但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>

当前回答

我正在更新这个答案,因为它非常有用。只需将readonly添加到输入。

所以形式是:

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

其他回答

如果你绝对必须有字段禁用和传递数据,你可以使用javascript输入相同的数据到一个隐藏字段(或只是设置隐藏字段太)。这将允许您禁用它,但仍然可以发布数据,即使您要发布到另一个页面。

我正在更新这个答案,因为它非常有用。只需将readonly添加到输入。

所以形式是:

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />
    <input type="textbox" name="Percentage" value="100" readonly/>
</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 -->
}

用RGBA值定义颜色

在样式下添加以下代码

<!DOCTYPE html>
<html>
<head>
<style>
#p7 {background-color:rgba(215,215,215,1);}
</style>
</head>
<body>
Disabled Grey none tranparent
<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

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

</form>

结果