ASP. NET MVC Dropdownlist

Source: Internet
Author: User

This article describes how to display DropDownList in a Web page.

Step 1: Add a method inside the control

         Public actionresult showdropdownlist ()        {            return  View ();        }

Step 2: Add code to the View section

@Html. DropDownList ("Department",NewList<selectlistitem> {     NewSelectListItem {Text ="IT", Value ="1", Selected =true},    NewSelectListItem {Text ="HR", Value ="2"},    NewSelectListItem {Text ="Payroll", Value ="3"},}, "Select Department")

The above section is an option to add DropDownList as a "manual", and if you want to read the content through the database, first add the context and then get the contents of the datasheet through the context.

 public   ActionResult Showdropdownlist () { Sampledatacontext db  = new   Sampledataco            ntext (); Viewbag.departments  = new  selectlist (db. Departments,   ", "  name   );         return   View (); }
@Html. DropDownList ("departments""select Department")

The data saved in the viewbag.departments is automatically displayed in the DropDownList.

If you want an item to be displayed when it is loaded, you can

New " DepartmentID " " Name ");

Change to:

New " DepartmentID " " Name ","1");

Here "1" refers to the ID of the display item.

But this approach is still more "stupid", we can set a property in the table called isselected (as shown in the table), the value of each option to determine which item is selected.

 PublicActionResult showdropdownlist () {Sampledatacontext db=NewSampledatacontext (); List<SelectListItem> Selectlistitems =NewList<selectlistitem>(); foreach(varDepartmentinchdb. Departments) {SelectListItem SelectListItem=NewSelectListItem {Text=Department. Name, Value=Department. Departmentid.tostring (), Selected= Department. Isselected.hasvalue? Department. Isselected.value:false        };    Selectlistitems.add (SelectListItem); } viewbag.departments=Selectlistitems; returnView ();}

The view side remains the same.

ASP. NET MVC Dropdownlist

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.