Form fields are null on POST

2019-09-20 12:38发布

I have simple contact form, this is the (view)model:

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

Controller:

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

View:

@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's Contact method is called. But param form has all fields as null:

enter image description here

1条回答
迷人小祖宗
2楼-- · 2019-09-20 13:04

You need public properties with get set in your Model not fields,Currently you have created fields in Model class which will not work for you:

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;}
}
查看更多
登录 后发表回答