【问题标题】:How to override the name and id properties of a select dropdown如何覆盖选择下拉列表的名称和 ID 属性
【发布时间】:2014-02-18 21:11:03
【问题描述】:

如何覆盖 HTML 选择下拉菜单的 id 和 name 属性?

我的 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。我喜欢为我的标记提供更具描述性的名称,例如国家。而且我也更喜欢让我的 name 和 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 属性更改为 Country 而 name 保留在 CountryId 中?

【问题讨论】:

  • @Html.DropDownListFor 的概念是您的视图模型也将用作表单提交模型,在这种情况下,您可以使用您的视图模型使用表单发布。在您的情况下,如果您只是想自定义表单发布变量,请使用 @Html.DropDownList("name", new SelectList(...), new { id = "id" })

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案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,其中提到的“名称”需要在 cmets 中大写。

【讨论】:

  • 好问题,我没有解释。
猜你喜欢
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多