【发布时间】:2011-01-22 17:01:05
【问题描述】:
这有什么问题?
@Html.DropDownListFor(x => x.Post.CategoryId, new SelectList(Model.Categories, "ID", "CategoryName"), "-- Please select --")
@Html.ValidationMessageFor(x => x.Post.CategoryId)
当我提交表单时,模型状态无效,并且此下拉列表被标记为错误,即使我从下拉列表中选择了一个值。
(顺便说一句,CategoryId 在我的帖子表中是一个 FK) 我已经添加了这个“伙伴”类作为部分
[MetadataType(typeof(Post_Validation))]
public partial class Post
{
}
class Post_Validation
{
[Required(ErrorMessage = "Please select a Category")]
public int CategoryId { get; set; }
}
控制器:
// GET: /News/Add
[Authorize]
public ActionResult Add()
{
var model = new AddPostViewModel() { Categories = categoryRepository.GetAllCategories(), Post = new Post(), IsEditMode=false };
return View(model);
}
//
// POST: /News/Add
[Authorize]
[HttpPost]
public ActionResult Add(AddPostViewModel model)
{
if (!ModelState.IsValid)
{
..etc
}
}
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-3 razor