Model binding dropdown selected value

2019-04-29 14:09发布

问题:

I have a model and that model has a public List<string> Hour { get; set; } and the constructor

public SendToList()
    {
        Hour = new List<string> { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" };
    }

My question is why don't I get a selected value for this

@Html.DropDownListFor(model => model.Hour, Model.Hour.Select( 
                x => new SelectListItem
                {
                    Text = x,
                    Value = x,
                    Selected = DateTime.Now.Hour == Convert.ToInt32(x)
                }
            ))

But I get a selected value here.

@Html.DropDownList("Model.Hour", Model.Hour.Select( 
                x => new SelectListItem
                {
                    Text = x,
                    Value = x,
                    Selected = DateTime.Now.Hour == Convert.ToInt32(x)
                }
            ))

What is the difference?

回答1:

Because you need to assign the selected value to your model.

So I would recommend you the following approach. Let's start with the view model:

public class MyViewModel
{
    // this will hold the selected value
    public string Hour { get; set; }

    public IEnumerable<SelectListItem> Hours 
    { 
        get
        {
            return Enumerable
                .Range(0, 23)
                .Select(x => new SelectListItem {
                    Value = x.ToString("00"),
                    Text = x.ToString("00")
                });
        } 
    }
}

you could populate this view model inside the controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            // Set the Hour property to the desired value
            // you would like to bind to
            Hour = DateTime.Now.Hour.ToString("00")
        };
        return View(model);
    }
}

and in your view simply:

@Html.DropDownListFor(
    x => x.Hour, 
    new SelectList(Model.Hours, "Value", "Text")
)