【问题标题】:Null model passed in MVC to controller when form is submitted提交表单时,在 MVC 中将空模型传递给控制器
【发布时间】: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


【解决方案1】:

我已经在我的环境中重现了这个问题,我所做的所有修复它只是将模型字段更新为如下所示的属性

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; }
}

【讨论】:

  • 谢谢霍萨姆。我以前没有注意到它。
猜你喜欢
  • 2012-05-31
  • 2020-08-14
  • 1970-01-01
  • 2011-07-27
  • 2014-10-17
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 2014-05-29
相关资源
最近更新 更多