Danieboy
Danieboy

Reputation: 4521

How Do I Get ID From Item In DropDownList?

This is a followup to my last thread: How Do I Create A HTML Select With Only Items In Database In Asp.Net Razor?

How do I get the ID from the item selected in the DropDownList? The idea is that the names shown in the dropdown are connected to a 'CustomerId'.

https://i.sstatic.net/km61P.png

PS I don't want to fill this thread with all the code from the last thread because it would get really cluttered and confusing so if you need to look at a reference from this code, look at the other thread.

HTML Code

@Html.LabelFor(m => m.SelectedCustomerId)
@Html.DropDownListFor(m => m.SelectedCustomerId, Model.CustomerID)

RegisterController

[HttpPost]
public ActionResult Register(string registername, string registerpassword, string registerconfirmpassword, int customerId)
{
    if (ModelState.IsValid)
    {     
    this.customerId = Request["CustomerID"]);

    //Register new user with this information
    //Removed for clarity
    return Redirect("/");
}

Upvotes: 0

Views: 730

Answers (1)

Andrei
Andrei

Reputation: 56696

Take another look at how you defined the drop down list:

@Html.DropDownListFor(m => m.SelectedCustomerId

This will be, roughly, rendered as:

<select name="SelectedCustomerId" id="SelectedCustomerId"

So the value of the drop down will be posted back as SelectedCustomerId=5 (or whatever value is selected). Therefore to capture it you need to declare your parameter with the same name (case insensitive afaik):

[HttpPost]
public ActionResult Register(..., int selectedCustomerId)

However there is another, arguably better, approach. Note that you already have 4 parameters in your action. This is not very readable already. Better approach here would be to define a model class, or reuse the same you already use to render the view, and make it the only parameter of your action. And then just use its properties, as they will be populated by the model binder:

[HttpPost]
public ActionResult Register(TheModelType model)
{
    model.SelectedCustomerId // to access the selected customer id

Upvotes: 1

Related Questions