我正在使用MVC4应用程序,并且有一个控制器允许用户输入一些数据。问题是我在从表单返回的所有属性中获取空值。我正在使用强类型模型,我没有看到任何名称冲突,如在几篇关于传递null模型的帖子中所建议的那样。 继承我的模特
public class NewsItemView
{
[Required]
public string NewsTitle;
public string NewsAuthor;
public string NewsSummary;
public string NewsDescription;
public bool NewsAllowComments;
[Required]
public string NewsContent;
public string NewsSourceName;
}
控制器动作(获取)
[HttpGet]
public ActionResult Create()
{
NewsItemView nv = new NewsItemView();
return View(nv);
}
查看:
@model NewsItemView
@using (Html.BeginForm("Create", "Service", FormMethod.Post, new { @id = "NewsForm" }))
{
@Html.LabelFor(model => model.NewsTitle)
@Html.EditorFor(model => model.NewsTitle)
<br />
@Html.LabelFor(model => model.NewsAuthor)
@Html.EditorFor(model => model.NewsAuthor)
<br />
@Html.LabelFor(model => model.NewsAllowComments)
@Html.EditorFor(model => model.NewsAllowComments)
<br />
@Html.LabelFor(model => model.NewsSummary)
@Html.EditorFor(model => model.NewsSummary)
<br />
@Html.LabelFor(model => model.NewsDescription)
@Html.EditorFor(model => model.NewsDescription)
<br />
@Html.LabelFor(model => model.NewsContent)
@Html.EditorFor(model => model.NewsContent)
<br />
@Html.LabelFor(model => model.NewsSourceName)
@Html.EditorFor(model => model.NewsSourceName)
<br />
<button type="submit" id="submitBtn">Create News</button>
}
控制器动作(帖子)
[HttpPost]
public ActionResult Create(NewsItemView newsModel)
{
//my code here
}
如果我使用FormsCollection,我可以使用索引提取值,任何想法为什么强类型模型不起作用?
答案 0 :(得分:2)
我已经在我的环境中重现了这个问题,而我所做的一切就是将模型字段更新为以下属性
public class NewsItemViewModel
{
[Required]
public string NewsTitle { get; set; }
public string NewsAuthor { get; set; }
public string NewsSummary { get; set; }
public string NewsDescription { get; set; }
public bool NewsAllowComments { get; set; }
[Required]
public string NewsContent { get; set; }
public string NewsSourceName { get; set; }
}