15

In my razor I am generating dropdown list like this.

    @{
        var listItems = new List<ListItem> 
        { 
              new ListItem { Text = "Home To School", Value = "0" }, 
              new ListItem { Text = "School To Home", Value = "1" } 
        };
    }

@Html.DropDownList("Direction", new SelectList(listItems),new {onchange = "getAlldata()"})

HTML generated from this is like this

<select id="Direction" name="Direction" onchange="getAlldata()">
<option>Home To School</option>
<option>School To Home</option>
</select>

but I want to generate HTML something like this

<select id="Direction" name="Direction" onchange="getAlldata()">
<option value="0">Home To School</option>
<option value="1">School To Home</option>
</select>

How can I do this.

2 Answers 2

29

Use it like this

@Html.DropDownList("Direction", new SelectList(listItems , "Value" , "Text"),new {onchange = "getAlldata()"})
Sign up to request clarification or add additional context in comments.

2 Comments

Where do you put the definition of the function "getAlldata()" ?
Or simply @Html.DropDownList("Direction", llistItems, new {onchange = "getAlldata()"}) - its pointless extra ovrhead to create a second SelectList from the existing one
6

Here are some examples of how to build DropDownList with Razor, like one with using SelectListItem:

public ActionResult Index()
{
  var db = new NorthwindEntities();
  IEnumerable<SelectListItem> items = db.Categories
    .Select(c => new SelectListItem
                   {
                     Value = c.CategoryID.ToString(), 
                     Text = c.CategoryName
                   });
  ViewBag.CategoryID = items;
  return View();
}

EDIT:

Check this:

@Html.DropDownList("Direction", new List<SelectListItem>
{
  new SelectListItem{ Text = "Home To School", Value = "0" },
  new SelectListItem{ Text = "School To Home", Value = "1" } 
},new {onchange = "getAlldata()"})

4 Comments

I have to generate my dropdown list in view only. Also It is static as shown in my question.
@vaibhavshah It was just an example of using collection of SelectListItem qouted from the article to show one way of doing this, I don't understand the -1. I added another way adapted to your data now.
@vaibhavshah Could you please explain this -1? I gave you article with different answers for this issue and quoted one of them. I see no reason of downvoting.
Where does the definition of getAlldata() go?

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.