【发布时间】:2018-04-10 00:01:38
【问题描述】:
我有以下视图模型:
public class CreateCaseViewModel
{
[Required]
public string Subject { get; set; }
[Required]
[DisplayName("Post Content")]
[UIHint("ForumEditor"), AllowHtml]
[DataType(DataType.MultilineText)]
public string PostContent { get; set; }
// some other dropdown properties
}
以下控制器动作:
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create(CreateCaseViewModel viewModel, FormCollection collection)
{
// Re-populate dropdowns
viewModel.Categories = _unitOfWork.CategoryRepository.GetCategories();
viewModel.Subject = collection["Subject"];
viewModel.PostContent = collection["Description"];
try
{
if (ModelState.IsValid)
{
// Do stuff
}
}
catch (DataException dex )
{
throw new ApplicationException("Something :", dex);
}
return View(viewModel);
}
正如您从上面的代码中看到的那样,我从 FormCollection 中的值手动将值分配给 PostContent。但是我仍然不断收到 modelstate is invalid - 我返回到视图并显示验证错误说“需要发布内容字段”
为什么模型状态无效?
【问题讨论】:
-
为什么要使用 FormCollection 并手动分配它?在您的视图模型中创建一个名为 Description 的新属性,并让模型绑定为您处理它
-
@Shyju 它是一个动态表单,表单结构存储为 xml,所以我无法创建专用的视图模型,因为我不知道表单上有多少字段或它们是什么叫。但是有一些必填字段,例如 Subject 和 PostContent,我想将它们映射到视图模型。这些字段将作为名称值对在数据库中进行排序。
标签: asp.net-mvc validation viewmodel modelstate