【发布时间】:2015-01-23 11:52:40
【问题描述】:
我正在使用 MVC4 应用程序,并且有一个控制器允许用户输入一些数据。问题是我在表单返回的所有属性中都得到了空值。我正在使用强类型模型,我没有看到任何名称冲突,正如一些关于传递空模型的帖子中所建议的那样。 这是我的模型
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;
}
控制器动作(get)
[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,我可以使用索引提取值,知道为什么强类型模型不起作用吗?
【问题讨论】:
-
您能否显示发送到您的创建操作的请求?
-
我唯一能想到的是你没有一个不带参数的模型的构造函数,但是你发布的代码看起来还可以。
-
@ChrisRedhead 这是默认构造函数的含义。
-
看起来模型绑定搞砸了。您可以尝试将您的模型发布功能减速更改为类似这样的 public ActionResult Create(NewsItemView m)
-
你是不是缺少模型属性上的getter和setter?
标签: c# asp.net-mvc model-binding