Search code examples
data-bindingrazortextdropdownlistfor

DropDownListFor binding to the text displayed not the underlying id (razor)


I have a razor (cshtml) file with a dropdownlistfor:

@Html.DropDownListFor(model => model.x_nme, (SelectList) ViewData["Y"]);

The SelectList is formed in the controller as:

var = new SelectList(xList, "id", "x_nme", current.id);

ViewData["Y"] = y_var;

I want the model to bind to the "x_nme" attribute, which displays correctly in the dropdown, but instead it binds to the id attribute.

I need the id attribute as this dropdown fills several fields in the form using javascript/ajax/jquery and I could as an alternative bind to a hidden field to get the name correct.

I was wondering if there is a way to directly bind the model => model.x_nme to the text in the drop-down instead of the underlying id w/o having to have a hidden field.

Thanks in advance.


Solution

  • ViewData["Y"] = new SelectList(xList, "Text", "Text");

    Then there is only text on the dropdown, so it will be selected!

    This actually works!