请帮我解决这个问题。 我无法为My Project验证DropdownList。 我的模型使用DataAnnontation:
public class Category
{
public int Id { get; set; }
public virtual IList<Product> Products { get; set; }
}
public class Product
{
[Required]
[StringLength(32)]
public string Id { get; set; }
[Required]
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
最后,创建视图的一些代码:
<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
@Html.DropDownList("CategoryId", String.Empty) @Html.ValidationMessageFor(x => x.CategoryId)</td>
}
答案 0 :(得分:1)
您需要使用@html.DropDownListFor()
答案 1 :(得分:0)
试试这个。
模型
public class YourViewModel
{
[Required]
public string CategoryId { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
表格
@using (Html.BeginForm())
{
@Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"),
"-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)
}