Asp.net mvc 当绑定到数据库时,下拉列表中的值默认为列表顶部的值
我正在构建一个用于数据输入的表单,但是用户必须填写的下拉列表之一是一个下拉列表,该列表由已更改为用户友好格式的枚举填充。下拉列表的默认选项为“请选择…”。但是,无论用户选择了什么,当单击“提交”按钮并将条目保存在数据库中时,保存的条目始终是第一个枚举,即列表顶部的值,我不知道为什么 模型如下:Asp.net mvc 当绑定到数据库时,下拉列表中的值默认为列表顶部的值,asp.net-mvc,forms,enums,html-helper,Asp.net Mvc,Forms,Enums,Html Helper,我正在构建一个用于数据输入的表单,但是用户必须填写的下拉列表之一是一个下拉列表,该列表由已更改为用户友好格式的枚举填充。下拉列表的默认选项为“请选择…”。但是,无论用户选择了什么,当单击“提交”按钮并将条目保存在数据库中时,保存的条目始终是第一个枚举,即列表顶部的值,我不知道为什么 模型如下: public enum Medium { [Description("Teleconference & Report")] Teleconference_Report, [
public enum Medium
{
[Description("Teleconference & Report")]
Teleconference_Report,
[Description("Email & Telephone")]
Email_Telephone
}
[Required]
[Display(Name = "Medium")]
public Medium Medium { get; set; }
以下是表单中的字段:
<div class="form-group">
@Html.LabelFor(model => model.Medium, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
@Html.DropDownList("MediumID", null, "Please select...", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Medium, "", new { @class = "text-danger" })
</div>
</div>
非常感谢您的帮助。假设您使用
GetEnumDescription
方法填充ViewBag.MediumList
,您需要绑定Medium属性而不是MediumID,并使用ViewBag.MediumList作为下拉列表的数据源:
<div class="form-group">
@Html.LabelFor(model => model.Medium, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
@Html.DropDownListFor(model => model.Medium, (List<SelectListItem>)ViewBag.MediumList, "Please select...", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Medium, "", new { @class = "text-danger" })
</div>
如果您仍然需要MediumId
属性-我认为您可以将其设置为calculate属性:
public int MediumId{
get{
return (int)this.Medium;
}
}
但是,无论用户选择了什么,当单击“提交”按钮并将条目保存在数据库中时,保存的条目始终是第一个枚举,即列表顶部的值,我不知道为什么
原因是enum基本上是一个int,它的默认值是0。以这种方式定义枚举时:
public enum Medium
{
[Description("Teleconference & Report")]
Teleconference_Report,
[Description("Email & Telephone")]
Email_Telephone
}
Teleconference\u Report
值为0,Email\u Telephone
值为1,这使得Teleconference\u Report
成为此枚举的默认值。由于您的Medium
属性没有正确绑定,因此它总是设置为默认的Teleconference\u Report
值。工作起来很有魅力。谢谢!
public ActionResult Create([Bind(Include = "Point,ApplicationID,MediumID,Frequency,StartDate,EndDate")] TouchPoint touchPoint)
<div class="form-group">
@Html.LabelFor(model => model.Medium, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-5">
@Html.DropDownListFor(model => model.Medium, (List<SelectListItem>)ViewBag.MediumList, "Please select...", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Medium, "", new { @class = "text-danger" })
</div>
public ActionResult Create([Bind(Include = "Point,ApplicationID,Medium,Frequency,StartDate,EndDate")] TouchPoint touchPoint)
public int MediumId{
get{
return (int)this.Medium;
}
}
public enum Medium
{
[Description("Teleconference & Report")]
Teleconference_Report,
[Description("Email & Telephone")]
Email_Telephone
}