Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc form not posting parameter values

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?

like image 887
user257655 Avatar asked May 19 '15 14:05

user257655


1 Answers

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!

like image 187
clement Avatar answered Oct 17 '22 02:10

clement