Last post Aug 22, 2017 03:37 PM by A2H
Member
1 Points
67 Posts
Aug 22, 2017 02:18 PM|sakuradata|LINK
<div> @{ List<SelectListItem> listItems = new List<SelectListItem>(); string test = "test"; string test2 = "test2"; listItems.Add(new SelectListItem() { Value = test, Text = test, Selected = test == item.Test ? true : false }); listItems.Add(new SelectListItem() { Value = test2, Text = test2, Selected = test2 == item.test2 ? true : false }); } @Html.DropDownList("Status", listItems, "Select Item") </div>
Question: Is it possibly to do it with HTML helper in relation to ASP.net MVC instead of having the code above?
I tried finding a solution to it but it doesn't work.
Thank you!
All-Star
50831 Points
9895 Posts
Aug 22, 2017 03:37 PM|A2H|LINK
sakuradata Is it possibly to do it with HTML helper in relation to ASP.net MVC instead of having the code above?
You can try below implementation
Create a folder called Helpers and then create a file called "DropdownlistHelper.cs"
Add the below code to class file we created now
public static class DropdownlistExtensions { public static MvcHtmlString CustomDropdownlist(this HtmlHelper helper, string name,string itemselected) { List<SelectListItem> listItems = new List<SelectListItem>(); string test = "test"; string test2 = "test2"; listItems.Add(new SelectListItem() { Value = test, Text = test, Selected = test == itemselected ? true : false }); listItems.Add(new SelectListItem() { Value = test2, Text = test2, Selected = test2 == itemselected ? true : false }); return System.Web.Mvc.Html.SelectExtensions.DropDownList(helper, name, listItems); } }
Now in your view first import the namespace.
@using WebApplication1.Helpers
Please note above namespace is as per my webapplication, you have to change this as per your application
Then you can use the helper like below
@Html.CustomDropdownlist("YourDropdowlistName","YourSelectedItemValue")
Sample Usage
@Html.CustomDropdownlist("Dropdowlist1","test2")
Refrence: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/views/creating-custom-html-helpers-cs
Member
1 Points
67 Posts
About HTML Helper
Aug 22, 2017 02:18 PM|sakuradata|LINK
Question:
Is it possibly to do it with HTML helper in relation to ASP.net MVC instead of having the code above?
I tried finding a solution to it but it doesn't work.
Thank you!
All-Star
50831 Points
9895 Posts
Re: About HTML Helper
Aug 22, 2017 03:37 PM|A2H|LINK
You can try below implementation
Create a folder called Helpers and then create a file called "DropdownlistHelper.cs"
Add the below code to class file we created now
Now in your view first import the namespace.
Please note above namespace is as per my webapplication, you have to change this as per your application
Then you can use the helper like below
Sample Usage
Refrence: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/views/creating-custom-html-helpers-cs
Aje
My Blog | Dotnet Funda