简体   繁体   English

使用EditorFor时,表单POST给出了空的模型字段

[英]Form POST gives empty model fields when using EditorFor

Currently I have a form which I am wanting to place in multiple views. 目前,我有一个要放在多个视图中的表单。 Currently when I submit this form, the model return has null for all it's values and i am unsure why. 目前,当我提交此表单时,模型返回的所有值都为null,我不确定为什么。

When I debug through it is reaching the POST event but the model values are null. 当我调试通过它到达POST事件,但模型值是null。 (not the model itself). (而不是模型本身)。

Contact Model 接触模型

public class ContactModel : BasePageModel
{
    public string Introduction { get; set; }
    public ContactForm Form { get; set; }
    public ContactModel(TreeNode node, ContactForm form = null) : base(node)
    {
        Introduction = node.GetEditableTextStringValue("Introduction", String.Empty);
        Form = form;
    }
}

View Model for the form 查看表格的模型

public class ContactForm
{
    public string Title { get; set; }
    public string FirstName { get; set; }
    ....
}

Controller 控制者

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SendContact(ContactForm model)
{
    // Do stuff
}

This is the view of the page I want to "embed" if you will the contact form I want to submit. 如果您要提交的联系表单,这是我要“嵌入”的页面的视图。

@model MVCApp.Models.PageModels.ContactModel
....
@using (Html.BeginForm("SendContact", "Contact", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.EditorFor(model => model.Form)
}

And the editor template of the Contact Form itself 还有联系表格本身的编辑器模板

@model MVCApp.Models.FormModels.ContactForm
....
@Html.LabelFor(model => model.Title)
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title, "")

@Html.LabelFor(model => model.FirstName)
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName, "")

....
<input type="submit" value="Submit" />

The form renders both parts (The surrounding text and fields) as well as the contact form correctly. 表单正确呈现了两个部分(周围的文本和字段)以及联系表单。 But as I said above when I click on submit the model that gets passed back in the POST to the controller (which it does hit through debugging) has all it's fields as null. 但是正如我上面说的,当我单击提交时,将在POST中传递回给控制器的模型(它确实通过调试命中)将其所有字段都设置为null。

Any pointers in where I may have gone wrong would be great. 我可能在哪里出错的任何指示都是很棒的。

Marking this as the answer since Stephens comment can't be marked as such. 由于斯蒂芬斯的评论无法被标记为答案,因此将其标记为答案。

Using Stephens suggestion, I changed the ActionResult to use 根据斯蒂芬斯的建议,我将ActionResult更改为使用

        public ActionResult SendContact([Bind(Prefix = "Form")]ContactForm model)

And it worked perfectly. 而且效果很好。 The fields and the model are populated correctly. 字段和模型正确填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM