Form fields are null on POST

2019-09-20 13:01发布

问题:

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:

回答1:

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