0
votes

I am trying to get my head around drop down lists with MVC, which appears to be failing me. I've been tinkering with the code shown below but can't get it right.

What I am trying to achieve is simple - hard coding some drop down options in the controller, have them appear in the Razor rendered html and when an option is selected, that selected value is bound back to the string property in the model.

With the code below I can't access li from within the View.

I've seen other guides but I haven't been able to make it work, is binding model the best option for me, given what I'm trying to achieve, or would ViewBag etc be better?

Could someone show me where I'm going wrong please?

Model

public class ViewModel {
    public string MyOption { get; set; } }

View

@model ViewModel
@Html.DropDownListFor(m => m.MyOption, li, "--Select--")

Controller

public ActionResult Index()
        {
            List<SelectListItem> li = new List<SelectListItem>();
            li.Add(new SelectListItem { Text = "Option One", Value = "option1" });
            li.Add(new SelectListItem { Text = "Option Two", Value = "option2" });
            return View(li);
        }
2

2 Answers

1
votes

You need to pass MyOption to view if you want to use it. A valid option would be to creaete a view model class containing all information you need to handle on your view

ViewModel

public class ViewModel
{
    public IList<SelectListItem> ItemList {get; set;}
    public string MyOption { get; set; }
}

View

@Html.DropDownListFor(m => m.MyOption, Model.ItemList, "--Select--")

Controller

public ActionResult Index()
{
    var li = new List<SelectListItem>();
    li.Add(new SelectListItem { Text = "Option One", Value = "option1" });
    li.Add(new SelectListItem { Text = "Option Two", Value = "option2" });
    var viewModel = new ViewModel 
    { 
        ItemList = li, 
        MyOption = [here your code to fill this] 
    }

    return View(viewModel);
}
0
votes

you need to make sure you are declaring your model in the view in order to access any attributes or modifiers to that model

@model Namespacehere.Models.modelclassname

then you should be able to use something like

@Html.DropDownListFor(m => m.MyOption, model, "--Select--")