POST上的表单字段为空

时间:2015-03-03 13:16:08

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-5

我有简单的联系表格,这是(查看)模型:

public class ContactForm
{
    [Required]
    public string Name;
    [Required]
    public string Email;
    [Required]
    public string Subject;
    [Required]
    public string Msg;
}

控制器:

public ActionResult Contact (ContactForm form)
{
    return RedirectToAction("Index");
}

查看:

@model myNamespace.ContactForm
...
@using (Html.BeginForm("Contact", "Home", FormMethod.Post))
{
    @Html.LabelFor(x => x.Name)
    @Html.TextBoxFor(x => x.Name)
    @Html.LabelFor(x => x.Email)
    @Html.TextBoxFor(x => x.Email)
    @Html.LabelFor(x => x.Subject)
    @Html.TextBoxFor(x => x.Subject)
    @Html.LabelFor(x => x.Msg)
    @Html.TextAreaFor(x => x.Msg)
    <button type="submit">Enviar</button>
}

调用Controller的Contact方法。但是param form将所有字​​段都设为null:

enter image description here

1 个答案:

答案 0 :(得分:5)

您需要在模型中使用get set公开properties fields,目前您已在模型类中创建了不适合您的字段:

public class ContactForm
{
[Required]
public string Name {get;set;}
[Required]
public string Email { get; set;}
[Required]
public string Subject {get;set;}
[Required]
public string Msg{get;set;}
}