无法设置文本区域和复选框以在 mvc5 中设置值

Not able to set textarea and checkbox to set value in mvc5

您好,我正在尝试在 mvc 5 中为文本区域和复选框设置 javascript + jquery 中的值,但它不起作用。

我的 javscript 代码是

 document.getElementById("UpdatetxtDescription").value = "abc";       
 document.getElementById("UpdateActive").checked = true;   

我的查看页面代码是

@Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", id = "UpdatetxtDescription" } })
@Html.CheckBoxFor(model => model.Active, new { htmlAttributes = new { @class = "form-control", id = "UpdateActive" } })

在控制台中我可以看到

<input data-val="true" data-val-required="The Active field is required." htmlattributes="{ class = form-control, id = UpdateActive }" id="Active" name="Active" type="checkbox" value="true">

<textarea cols="20" htmlattributes="{ class = form-control, id = UpdatetxtDescription }" id="Description" name="Description" rows="2"></textarea>

我可以用 id="Description" 和 id="Active" 设置值 nut 因为我有 2 个复选框和 2 个文本区域 我不能使用那个 id 因为两个控件都有相同的 id textarea 的描述和 Active 的复选框

第二个textarea和checkbox如下,我设置的不同

@Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", id = "txtDescription", rows = "3" } })
@Html.CheckBoxFor(model => model.Active, new { htmlAttributes = new { @class = "form-control", id = "txtDescription" } })

但在控制台中我可以看到 Id 为

<textarea cols="20" htmlattributes="{ class = form-control, id = txtDescription, rows = 3 }" id="Description" name="Description" rows="2"></textarea>
<input data-val="true" data-val-required="The Active field is required." htmlattributes="{ class = form-control, id = txtDescription }" id="Active" name="Active" type="checkbox" value="true">

对于有效结构,id 在同一文档中应该是唯一的,如果您不能更改它,那么您可以使用 jQuery 选择器来处理这种重复,例如 :

$('[id="Description"]:eq(0)') //Select the first element with id "Description"
$('[id="Description"]:eq(1)') //Select the second element with id "Description"

第二个元素相同 input :

$('[id="Active"]:eq(0)') //Select the first element with id "Active"
$('[id="Active"]:eq(1)') //Select the second element with id "Active"

希望对您有所帮助。

您正在以错误的方式设置 HTML 助手的 htmlAttributes 参数。如果您看到生成的 HTML,您可以看到 idclass 没有被设置。但是一个名为 htmlAttributesattribute 本身是这样添加的:

<textarea cols="20" htmlattributes="{ class = form-control, id = UpdatetxtDescription }"></textarea>

所以你应该把它改成:

@Html.TextAreaFor(model => model.Description, new { @class = "form-control", id = "UpdatetxtDescription" })
@Html.CheckBoxFor(model => model.Active, new { @class = "form-control", id = "UpdateActive" })

@Html.TextAreaFor(model => model.Description, new { @class = "form-control", id = "txtDescription", rows = "3" })
@Html.CheckBoxFor(model => model.Active, new { @class = "form-control", id = "txtDescription" })

(PS: 如果您要提交此表单,则只有一个文本区域和复选框将绑定到模型,因为您正在创建多个具有相同 name. 属性的输入)