0

I am new to MVC so probably confused . can somebody please explain me the dropdown in razor.my questions are-

  • What is the difference in dropdownlist and dropdownlistfor
  • how do i Pass ID column of my database table as value and NAME column as text.
  • How do i add "other" to the dropdownlist.
  • how do i access the selectedlistitem in code behind.

if possible please explain with an example.

1 Answer 1

1
  1. DropDownList is generated by code like this:

    @Html.DropDownList("PersonId", new SelectList(Model.People, "Id", "Text");

    On the other hand, DropDownListFor is generated like this:

    @Html.DropDownListFor(m => m.PersonId, new SelectList(Model.People, "Id", "Text")
    Problem with DropDownList is that it has a magic string and if you decide to refactor the model later on, there's a high change you'll forget to change the magic string too.

  2. You could do a LINQ query like this:

    var datalist = New SelectList(from x in _peopleService
                                  select new SelectListItem { Text = x.Name, Value = x.Id});
    If you don't have a service or an ORM between it you need to apply it to your situation, but you can generate a list like that.

  3. After nr 2, you can

    datalist.Add(new SelectListItem() { Text = "Other", Value = "-1"});
    Also you have to put that datalist in your viewmodel/model that is passed to the View, so you can generate a selectlist item with that. In this case you could just do:
    @Html.DropDownListFor(x => x.PersonId, Model.PersonList);
    if you stored the list as PersonList in Model.

  4. In your Viewmodel (Well, model in mvc) you have a property where the selected item will be stored, look at the 1st question - In this instance the selected item's id will be stored in the PersonId property.
Sign up to request clarification or add additional context in comments.

1 Comment

you could probably mention how enums and dropdowns work together aswell. I usually have an enum for a dropdown. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.