我有一个html选择器,我想在我的表单中使用我的“model => model.type”的选定值。有没有办法将@Html.EditorFor(model => model.type)
中的值设置为选择器的值?
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Bet</legend>
<div class="editor-label">
@Html.LabelFor(model => model.type)
</div>
<div class="editor-field">
<select id ="type">
<option value="Football">Football</option>
<option value="Rugby">Rugby</option>
<option value="Horse Racing">Horse Racing</option>
</select>
@Html.EditorFor(model => model.type)
@Html.ValidationMessageFor(model => model.type)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
答案 0 :(得分:20)
您可以尝试使用以下选项:
型号:
public string Type { get; set; }
public IEnumerable<SelectListItem> TypeList
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "Football", Value = "Football"},
new SelectListItem { Text = "Rugby", Value = "Rugby"},
new SelectListItem { Text = "Horse Racing", Value = "Horse Racing"}
};
}
}
HTML(Razor):
@Html.DropDownListFor(model => model.Type, Model.TypeList)
OR
HTML(Razor):
@Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, Model.Type))
答案 1 :(得分:2)
@ andresdescalzo的解决方案(最后一个)适用于一个小改动:
@Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, "Rugby"), htmlAttributes: new { @class = "form-control" })
首先:为下拉列表添加所选项目(例如&#34; Rugby&#34;)
第二次:删除上一次Model.Type
并添加htmlAttributes
PS:SelectedList打开括号在所选列表项后关闭(此处为&#34; Rugby
&#34;)
答案 2 :(得分:1)
@andresdescalzo提供的解决方案仅在我们将模型从Controller传递给视图时才起作用。
public class SomeController : Controller
{
public ActionResult SomeAction()
{
return View(new SomeModelWithIEnumerationsSelectListItem())
}
}
答案 3 :(得分:0)
对现有答案的补充:如果在实现@ andresdescalzo解决方案时遇到异常“对象引用未设置为对象的实例”,则需要:
第二种可以这样做:
@{ var tempModel = new YourNameSpace.Models.YourModel(); }
@Html.DropDownListFor(model => model.Type, tempModel.TypeList, Model.Type))
答案 4 :(得分:0)
这是剃刀视图
<div class="editor-field col-md-3">
@Html.DropDownListFor(model => model.Servers,
Model.AvailableServers,new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.SqlServerName)
</div>
从控制器动态下拉
List<SelectListItem> ServersAvailable = new List<SelectListItem>();
bool IdSelected = false;
ServersAvailable.Add(new SelectListItem { Text = "......Select your server name......", Value = "" });
for (int i = 0; i < dt.Rows.Count; i++)
{
ServersAvailable.Add(new SelectListItem
{
Text = dt.Rows[i].ItemArray[0].ToString(),
Value = dt.Rows[i].ItemArray[0].ToString(),
Selected = IdSelected
});
}