Asp.net mvc form does not publish parameter values

I am amazed at what I think is a rather stupid issue, which I obviously missed out on something simple.

I made a simple asp.net mvc site (.net 4.5) and changed the index to have a simple form that I would like to just send back to myself and bind 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 message method

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

I get nothing when the page is published. Also in the debugger, I see that the method gets hit, however, all the parameters are zero, although I filled out the form.

Am I missing something obvious?

+5
source share
1 answer

You just forgot 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 using model binding instead of some strings or int. If you use them correctly, model binding will work effortlessly:

Model:

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

On 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 the controller:

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

Using the model, you can also add validation, etc. Directly in the model, and then ASP.NET MVC can place validation both in the external interface with jQuery validation and in the internal interface (if (ModelState.IsValid)). Many benefits to using models!

+11
source

All Articles