¿De dónde obtiene DropDownListFor el modelo?

You can create a dropdownlist using

@Html.DropDownListFor(model => model.SelectedId, model.DropDownItems);

but where does DropDownListFor get the value to pass into the model => model.SelectedId lambda from?

preguntado el 02 de febrero de 12 a las 11:02

1 Respuestas

SelectedId is just the integer of the field in the model.

the model is passed in from the controller using

return View(myModel);

And the model can be defined in the view at the top

@model mymodelnamespace.RoomBookingInsert

So the dropdownbox's value is set as the SelectedId field in your model.

A proper field name for example would be RoomNo if that clarifies it better.

@Html.DropDownListFor(model => model.RoomNo, model.Rooms);

Mientras model.DropDownItems (o model.Rooms in my example) Contains a item with the value of that attribute, it will set it as the selected item in the list as default.

Edit:

If you are using viewbag, rather than the model, instead use DropDownList. (each input has a for extension for use with models)

@Html.DropDownList("RoomNo", 
       new SelectList(ViewBag.Rooms as System.Collections.IEnumerable ?? Enumerable.Empty<SelectListItem>(), "RoomNo", "RoomName"),
       new { @value = @ViewBag.RoomNo})

This above, creates an input form with id RoomNo,

y usa un SelectList that will default to empty if null. The fields that defined the values and text shown are set at the end of the select list parameters.

The last bit sets the default value to the contents of @ViewBag.RoomNo.

You can also create the select list in the controller, and then simply set the dropdown options to the viewbag.myselectList entidad.

Respondido 02 Feb 12, 17:02

What if the 'model' you want to use isn't the 'official' model, but some data passed in the ViewBag? - thecoop

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.