2016-07-24 10 views
0

Ich möchte ein Dropdown mit MVC und Raxor anzeigen erstellen. Obwohl ich in der Lage bin, ein Dropdown zu machen, aber ich weiß nicht, wie ID und Wert innerhalb des Dropdown-Tags gesetzt werden.wie MVC Razor View Dropdown mit ID und Text innerhalb der <option> Tag erstellen?

Controller:

public ActionResult Index() 
{ 
    SelectList dd = new SelectList(new[] { "Option1", "Option2" });//i want to set id 1 and 2 for Option1 and 2 respectively   
    ViewBag.dd = dd; 
    return View(); 
} 

Ausblick:

@Html.DropDownList("vimalDD",new SelectList(new[]{"VImal","Raturi"})) 
    @Html.DropDownList("vimalDD", (SelectList)ViewBag.dd) 
    @Html.DropDownList("Selected", (IEnumerable<SelectListItem>)ViewBag.dd, "First Option", new { name = "Name", id = "id" }) 
    @Html.DropDownList("vimalDD", (IEnumerable<SelectListItem>)ViewBag.dd , " -- Select -- ", new { id = "Job_DefaultProfitCenter" }) 
    @Html.DropDownList("vimalDD", (IEnumerable<SelectListItem>)ViewBag.dd, "--Choose Your City--") 

Ich möchte Drop-Down-Ausgabe als:

<select id="anything" name="Anything"> 
<option id="1">option1</option> 
<option id="2">option2</option> 
</select> 
+1

Erstellen Sie ein 'IEnumerable ' und legen Sie die Eigenschaften "Value" und "Text" fest. –

+0

schreiben Sie bitte die Codesyntax, um IEnumerable zu erstellen. und wo es im Controller erstellt werden muss oder @Stephen Mücke anzeigen – vimalraturi

+1

Im Controller - 'ViewBag.dd = neue Liste {new SelectListItem {Value =" 1 ", Text =" option1 "}, neues SelectListItem {Value = "2", Text = "option2"}} 'und in der Ansicht' @ Html.DropDownList ("vimalDD", (IEnumerable ) ViewBag.dd) aber das alles ist eine schreckliche Übung. Verwenden Sie ein Ansichtsmodell und die stark typisierte 'DropDownListFor()' Methode. –

Antwort

0
public ActionResult Index() 
{ 

    ViewBag.dd = new List<SelectListItem>{ new SelectListItem{ Value = "1", Text = "option1" }, new SelectListItem{ Value = "2", Text = "option2" } } 
    return View(); 
} 

Innenansicht Seite:

@Html.DropDownList("vimalDD", (IEnumerable<SelectListItem>)ViewBag.dd)