Thursday, September 7, 2017

Bind Html.DropDownList with static items


Method 1:
 @Html.LabelFor(m => m.Name, new { @class = "control-label" })
                    @{
                        var listItems = new List<System.Web.Mvc.SelectListItem>();
                        listItems.Add(new SelectListItem { Text = "name1", Value = "1" });
                        listItems.Add(new SelectListItem { Text = "name2", Value = "2" });
                        listItems.Add(new SelectListItem { Text = "name3", Value = "3" });
                    }
                    @Html.DropDownListFor(m => m.Name, listItems)


Method 2:

@{
            var domainsList = new SelectList(new []
            {
                new SelectListItem { Text = ".Com", Value = ".com", Selected = true },
                new SelectListItem { Text = ".Shopping", Value = ".shopping"},
                new SelectListItem { Text = ".Org", Value = ".org"},
                new SelectListItem { Text = ".Net", Value = ".net"},
                new SelectListItem { Text = ".AE", Value = ".ae"},
                new SelectListItem { Text = ".Info", Value = ".info"},
            }, "Value", "Text");
        }
        @Html.DropDownList("TopLevelDomains", domainsList)

Method 3:

It is a best practice not to create the SelectList in the view. You should create it in the controller and pass it using the ViewData.

Example:

var list = new SelectList(new []
{
    new { ID = "1", Name = "name1" },
    new { ID = "2", Name = "name2" },
    new { ID = "3", Name = "name3" },
},
"ID", "Name", 1);

ViewData["list"]=list;
return View();
you pass to the constratctor: the IEnumerable objec,the value field the text field and the selected value.

in the View:

<%=Html.DropDownList("list",ViewData["list"] as SelectList) %>

No comments:

Change default Port on Next.js app

 If any other app or process is running on port 3000 , you will get this error in your terminal Port 3000 is already in use. error Command f...