I have seen many developers who are still confused about the Dropdownlist HTML helper in MVC.
Syntax:-
@Html.DropDownList("dList")
this is the basic Syntax for Dropdownlist.
There are so many constructors used for Dropdownlist.
1. @Html.DropDownList("ddlDropDown", new List<SelectListItem>
{
new SelectListItem{ Text="Zero", Value = "0" },
new SelectListItem{ Text="One", Value = "1" },
new SelectListItem{ Text="Two", Value = "2" },
new SelectListItem{ Text="Three", Value = "3" },
new SelectListItem{ Text="Four", Value = "4" }
}
)
The output of this Dropdownlist :-

If you want to show optional option in the dropdownlist then you have to add an optional value in this syntax :-
@Html.DropDownList("ddlDropDown", new List<SelectListItem>
{
new SelectListItem{ Text="Zero", Value = "0" },
new SelectListItem{ Text="One", Value = "1" },
new SelectListItem{ Text="Two", Value = "2" },
new SelectListItem{ Text="Three", Value = "3" },
new SelectListItem{ Text="Four", Value = "4" }
},"Select Value"
)
OUTPUT:-

2. @Html.DropDownList("ddlServicePlan", new SelectList(@Model.Plans, "Value", "Text"),"Select Value")
Syntax:-
@Html.DropDownList("dList")
this is the basic Syntax for Dropdownlist.
There are so many constructors used for Dropdownlist.
1. @Html.DropDownList("ddlDropDown", new List<SelectListItem>
{
new SelectListItem{ Text="Zero", Value = "0" },
new SelectListItem{ Text="One", Value = "1" },
new SelectListItem{ Text="Two", Value = "2" },
new SelectListItem{ Text="Three", Value = "3" },
new SelectListItem{ Text="Four", Value = "4" }
}
)
The output of this Dropdownlist :-

If you want to show optional option in the dropdownlist then you have to add an optional value in this syntax :-
@Html.DropDownList("ddlDropDown", new List<SelectListItem>
{
new SelectListItem{ Text="Zero", Value = "0" },
new SelectListItem{ Text="One", Value = "1" },
new SelectListItem{ Text="Two", Value = "2" },
new SelectListItem{ Text="Three", Value = "3" },
new SelectListItem{ Text="Four", Value = "4" }
},"Select Value"
)
OUTPUT:-

2. @Html.DropDownList("ddlServicePlan", new SelectList(@Model.Plans, "Value", "Text"),"Select Value")
public List<ListItem> Plans
{
get
{
List<ListItem> items = new List<ListItem>
{
new ListItem{ Text="Zero", Value = "0" },
new ListItem{ Text="One", Value = "1" },
new ListItem{ Text="Two", Value = "2" },
new ListItem{ Text="Three", Value = "3" },
new ListItem{ Text="Four", Value = "4" },
};
return items;
}
}
we define this Plans property in Any model.
No comments:
Post a Comment