MVC3 DropDownListFor - a simple example?
Asked Answered
D

4

112

I'm having trouble with DropDownListFor in my MVC3 app. I was able to use StackOverflow to figure out how to get them to appear on the View, but now I don't know how to capture the values in its corresponding properties on the View Model when it's submitted. In order to get this to work I had to create an inner class that had an ID and a value property, then I had to use an IEnumerable<Contrib> to satisfy the DropDownListFor parameter requirements. Now, however, how is MVC FW supposed to map the value that is selected on this drop-down back into the simple string property on my view model?

public class MyViewModelClass
{
    public class Contrib
    {
        public int ContribId { get; set; }
        public string Value { get; set; }
    }

    public IEnumerable<Contrib> ContribTypeOptions = 
        new List<Contrib>
        {
            new Contrib {ContribId = 0, Value = "Payroll Deduction"},
            new Contrib {ContribId = 1, Value = "Bill Me"}
        };

    [DisplayName("Contribution Type")]
    public string ContribType { get; set; }
}

In my View I place the dropdown on the page like this:

<div class="editor-label">
    @Html.LabelFor(m => m.ContribType)
</div>
<div class="editor-field">
    @Html.DropDownListFor(m => m.ContribTypeOptions.First().ContribId, 
             new SelectList(Model.ContribTypeOptions, "ContribId", "Value"))
</div>

When I submit the form the ContribType is (of course) null.

What is the correct way to do this?

Dibs answered 22/8, 2011 at 3:47 Comment(0)
R
166

You should do like this:

@Html.DropDownListFor(m => m.ContribType, 
                new SelectList(Model.ContribTypeOptions, 
                               "ContribId", "Value"))

Where:

m => m.ContribType

is a property where the result value will be.

Reduplicate answered 22/8, 2011 at 5:52 Comment(7)
THANK YOU!!! Sergey, this is exactly what I have been looking for for many hours.Dibs
Thanks :) for your answer Is there any way to show "-- Select--" from here. ?Nichols
@VeeKeyBee, you can add new item to the list contribTypeOptions, for example new Contrib {ContribId = -1, Value = "Please Select"} and it will be shown in dropdown list. Than you can check if ContribType is -1 this is means that user haven't selected any valueReduplicate
that the way I am just doing .. But for dropdownlist we can give some optionsNichols
You can do this: @Html.DropDownListFor(m => m.ContribType, new SelectList(Model.ContribTypeOptions, "ContribId", "Value", Model.ContribTypeOptions.First().ContribId), "Select, please")Reduplicate
@SergeyGavruk. This answer has been used as a dupe on a few recent questions but is confusing some users because of the statement And the last param of Select list constructor is a selected value - The last parameter is ignored by the method (which internally builds its own SelectList). Its the value of the property (ContribType) which determines what is selected (that's how model binding works) and the code should just be @Html.DropDownListFor(m => m.ContribType, new SelectList(Model.ContribTypeOptions, "ContribId", "Value") Can you please edit the answer to correct.Udder
Can anyone please let me know how to use this solution when dropdown values are coming from database?Guenevere
T
6

For binding Dynamic Data in a DropDownList you can do the following:

Create ViewBag in Controller like below

ViewBag.ContribTypeOptions = yourFunctionValue();

now use this value in view like below:

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                   "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please")
Tanner answered 13/5, 2013 at 14:8 Comment(0)
I
6

I think this will help : In Controller get the list items and selected value

public ActionResult Edit(int id)
{
    ItemsStore item = itemStoreRepository.FindById(id);
    ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 
                                        "Id", "Name",item.CategoryId);

    // ViewBag to pass values to View and SelectList
    //(get list of items,valuefield,textfield,selectedValue)

    return View(item);
}

and in View

@Html.DropDownList("CategoryId",String.Empty)
Imbue answered 14/11, 2013 at 12:33 Comment(1)
It's usually not a god pattern to expose your repository to the View like this.Greenlet
S
0
     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

Here Value is that object of model where you want to save your Selected Value

Seline answered 20/1, 2018 at 18:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.