如何覆盖HTML选择下拉列表的ID和名称属性?
我的HTML中有以下标记来生成选择下拉列表:
@Html.DropDownListFor(
m => m.CountryId,
new SelectList(Model.Countries, "Id", "Name", Model.CountryId),
"-- Select --",
new { @class = "form-control" }
)
上面代码的输出如下所示:
<select name="CountryId" id="CountryId" data-val-required="Country is required" data-val-number="The field CountryId must be a number." data-val="true" class="form-control">
<option value="">-- Select --</option>
<option value="1">Country 1</option>
<option value="2">Country 2</option>
<option value="3">Country 3</option>
<option value="4">Country 4</option>
</select>
我看到它使name和id属性都等于CountryId。我喜欢我的标记更具描述性的名称,比如国家。而且我也希望我的名字和id属性具有相同的描述/名称。所以我尝试了以下内容:
@Html.DropDownListFor(
m => m.CountryId,
new SelectList(Model.Countries, "Id", "Name", Model.CountryId),
"-- Select --",
new { id = "Countries", name = "Countries", @class = "form-control" }
)
上面代码的输出如下所示:
<select name="CountryId" id="Countries" data-val-required="Country is required" data-val-number="The field CountryId must be a number." data-val="true" class="form-control">
<option value="">-- Select --</option>
<option value="1">Country 1</option>
<option value="2">Country 2</option>
<option value="3">Country 3</option>
<option value="4">Country 4</option>
</select>
为什么只有id属性更改为Countries且名称保留在CountryId?
答案 0 :(得分:1)
就是这种情况,因为该属性需要大写(Name
):
@Html.DropDownListFor(
m => m.CountryId,
new SelectList(Model.Countries, "Id", "Name", Model.CountryId),
"-- Select --",
new { id = "Countries", Name = "Countries", @class = "form-control" }
)
这是类似问题的answer,其中“姓名”的引用需要在评论中大写。