我是不是有点晚了?
更改枚举类型的值并不是很令人满意。
两者都没有更改模型属性以使其可以为空,然后添加一个 [Required] 属性来防止它可以为空。
我建议使用 ViewBag 来设置下拉菜单的默认选择值。
下面控制器的第 4 行是唯一重要的。
编辑:啊...新手...我的第一个想法是使用 ModelState.SetModelValue 因为我的新手本能阻止我简单地尝试在 ViewBag 中设置所需的值,因为下拉菜单是绑定到模型。我肯定有一个问题:它会绑定到模型的属性,而不是 ViewBag 的属性。我错了:ViewBag 没问题。我更正了代码。
这是一个例子。
型号:
namespace WebApplication1.Models {
public enum GoodMusic {
Metal,
HeavyMetal,
PowerMetal,
BlackMetal,
ThashMetal,
DeathMetal // . . .
}
public class Fan {
[Required(ErrorMessage = "Don't be shy!")]
public String Name { get; set; }
[Required(ErrorMessage = "There's enough good music here for you to chose!")]
public GoodMusic FavouriteMusic { get; set; }
}
}
控制器:
namespace WebApplication1.Controllers {
public class FanController : Controller {
public ActionResult Index() {
ViewBag.FavouriteMusic = string.Empty;
//ModelState.SetModelValue( "FavouriteMusic", new ValueProviderResult( string.Empty, string.Empty, System.Globalization.CultureInfo.InvariantCulture ) );
return View( "Index" );
}
[HttpPost, ActionName( "Index" )]
public ActionResult Register( Models.Fan newFan ) {
if( !ModelState.IsValid )
return View( "Index" );
ModelState.Clear();
ViewBag.Message = "OK - You may register another fan";
return Index();
}
}
}
查看:
@model WebApplication1.Models.Fan
<h2>Hello, fan</h2>
@using( Html.BeginForm() ) {
<p>@Html.LabelFor( m => m.Name )</p>
<p>@Html.EditorFor( m => m.Name ) @Html.ValidationMessageFor( m => m.Name )</p>
<p>@Html.LabelFor( m => m.FavouriteMusic )</p>
<p>@Html.EnumDropDownListFor( m => m.FavouriteMusic, "Chose your favorite music from here..." ) @Html.ValidationMessageFor( m => m.FavouriteMusic )</p>
<input type="submit" value="Register" />
@ViewBag.Message
}
Without the "ModelState.SetModelValue or ViewBag.FavouriteMusic = string.Empty" line in the model Index action the default selected value would be "Metal" and not "Select your music..."