asp.net mvc form not posting parameter values

2020-06-17 05:01发布

问题:

I'm hitting what I think is a pretty stupid issue that I am obviously missing something simple on.

I made a simple asp.net mvc site (.net 4.5) and changed the index to have a simple form that I'd like to just post back to itself and spit back the variables.
here is my form

@using(Html.BeginForm())
{
    <input type="text" class="form-control" id="empId" placeholder="Enter EmployeeId (ex. 999999)">
    <input type="text" class="form-control" id="account" placeholder="Enter account)">
    <input type="email" class="form-control" id="email" placeholder="Enter email">
    <input type="submit" class="btn btn-default" value="Submit" />
}

and here is my post method

[HttpPost]
public ActionResult Index(string empId, string account, string email)
{
    return Content(Request["empId"]);
}

I get nothing back when the page posts. Also in the debugger I can see that the method gets hit, however all the parameters are null even though I filled in the form.

Am I missing something obvious?

回答1:

You just forget the name attribute:

@using(Html.BeginForm())
{
    <input type="text" class="form-control" name="empId" id="empId" placeholder="Enter EmployeeId (ex. 999999)">
    <input type="text" class="form-control" name="account" id="account" placeholder="Enter account)">
    <input type="email" class="form-control" name="email" id="email" placeholder="Enter email">
    <input type="submit" class="btn btn-default" value="Submit" />
}

I always recommend to use model binding instead of some strings or int. If you use them well, it will make the model binding work effortlessly:

Model:

public class ExampleModel
{
public int empId { get; set; }
public string account{ get; set; }
public string email{ get; set; }
}

In the Razor page:

@using(Html.BeginForm())
    {
        @Html.EditorFor((m => m.intempId, new { @class = "form-control" } ))
        @Html.EditorFor((m => m.account, new { @class = "form-control" }))
        @Html.EditorFor((m => m.email, new { @class = "form-control" }))
    }

and then in controller:

[HttpPost]
public ActionResult Index(ExampleModel model)
{
    return Content(model.empId);
}

With the model, you can also add validation and so on, directly on the model and then ASP.NET MVC can put validation in both front-end with jQuery validation and back-end (if (ModelState.IsValid)). Lots of benefits to use models!