Asp.net mvc MVC SelectListHelper
我使用MVC和Razor。我的模型类有一个BrandId和Brands属性。我从数据库中填充Brands,并与helper一起使用。但当我提交表单时,它无法验证。因为BrandId是整数。但我无法将此属性的默认值设置为0。它的默认值是空格。我能做什么?多谢各位Asp.net mvc MVC SelectListHelper,asp.net-mvc,razor,view-helpers,Asp.net Mvc,Razor,View Helpers,我使用MVC和Razor。我的模型类有一个BrandId和Brands属性。我从数据库中填充Brands,并与helper一起使用。但当我提交表单时,它无法验证。因为BrandId是整数。但我无法将此属性的默认值设置为0。它的默认值是空格。我能做什么?多谢各位 //my model public class ProductViewModel { public int BrandId { get; set; } public IEnumerable<SelectListIte
//my model
public class ProductViewModel
{
public int BrandId { get; set; }
public IEnumerable<SelectListItem> Brands { get; set; }
}
//in my controller
public ActionResult Create(int id)
{
var prodGroup = id > 0 ? _prodGroupService.Get(id) : new ProdGroup();
return View(new ProdGroupViewModel
{
//How can i set default value to zero?
Brands = new SelectList(_brandService.GetAll(), "BrandId", "BrandName"),
});
}
//in my view
<div class="form-group">
<label class="col-md-3 control-label">Brand</label>
<div class="col-md-9">
//How can i set default value to zero?
@Html.DropDownListFor(model => model.BrandId, Model.Brands, "Choose", new { @class = "form-control" })
</div>
</div>
您可以将默认值设置为:
public class Person {
private const int DEFAULT_BrandId = 18;
private int _brandId = DEFAULT_BrandId ;
[DefaultValue(DEFAULT_BrandId )]
public int BrandId {
get { return _brandId; }
set { _brandId = value; }
}
}
不确定我是否理解,但如果您想验证是否选择了值而不是选择标签,则可以在我提交表单未验证时,将属性设置为可为null的int并添加[Required]attributeStephen。因为brands的下拉列表的默认值是空格。我想把它归零。如果它是零,那么它将验证是可以的。你说它是一个空格是什么意思?回发的值将为null或所选选项的值。它不能是一个空格,因为这不是inti的有效值。我的下拉列表是这样的,请选择一个。但我想选一个你为什么要这么做?但我想您需要为每个选项创建一个SelectListItem,然后在列表的开头插入一个值为0、文本为Choose的额外SelectListItem