Detailed description of ASP. net mvc drop-down box Binding four methods, asp. netmvc

Source: Internet
Author: User

Detailed description of ASP. net mvc drop-down box Binding four methods, asp. netmvc

Preface

In the last two sections, we talked about the file upload issue. The question about this upload is not over yet. I am also taking the time to split large files and display the progress. If this is done, I will post it again, to avoid delay in learning other MVC content, let's talk about several methods of binding enumeration in the MVC drop-down box today.

Topic Introduction

Generally, data is bound to the drop-down list in several cases.

(1) the data in the drop-down box is written to death. We can directly provide the dead code.

(2) the data in the drop-down list is read from the database for display.

(3) Use enumeration in the drop-down list.

(4) The selected value in the drop-down box changes the value in the other drop-down box.

The binding in the drop-down box is probably the above four methods. Next we will crack them one by one, and we will use Bootstrap to show the style. By the way, we will also review Bootstrap.

Hard coding in the drop-down box [1]

We provide the following data in the Controller and use ViewBag for transmission.

      ViewBag.hard_value = new List<SelectListItem>() {         new SelectListItem(){Value="0",Text="xpy0928"},        new SelectListItem(){Value="1",Text="cnblogs"}      };

Bind the following data:

 @Html.DropDownList("hard-code-dropdownlist", new SelectList(ViewBag.hard_value, "Value", "Text"), new { @class = "btn btn-success dropdown-toggle form-control" })

Let's take a look at the effect:

Read the database from the drop-down list [2]

To read the database, we will give a class test and then OK, and give the default selected value, the test class:

public class BlogCategory    {      public int CategoryId { get; set; }      public string CategoryName { get; set; }    }

Bind ViewBag to pass the value:

// Read var categoryList = new List <BlogCategory> () {new BlogCategory () {CategoryId = 1, CategoryName = "C #"}, new BlogCategory () from the database () {CategoryId = 2, CategoryName = "Java"}, new BlogCategory () {CategoryId = 3, CategoryName = "JavaScript"}, new BlogCategory () {CategoryId = 4, categoryName = "C" }}; var selectItemList = new List <SelectListItem> () {new SelectListItem () {Value = "0", Text = "all ", selected = true }}; var selectList = new SelectList (categoryList, "CategoryId", "CategoryName"); selectItemList. addRange (selectList); ViewBag. database = selectItemList;

Slightly modify the View:

@Html.DropDownList("database-dropdownlist", ViewBag.database as IEnumerable<SelectListItem>, new { @class = "btn btn-success dropdown-toggle form-control" })

See the results:

ViewBag. database needs to be converted; otherwise, the following error occurs:

CS1973: "System. Web. Mvc. HtmlHelper <dynamic>" does not have an applicable method named "DropDownList", but there seems to be an extension method with this name. The scaling method cannot be dynamically scheduled. Consider forcibly converting dynamic parameters or calling the extension method without using the extension method syntax.

Enumeration bound to the drop-down box [3] (1)

We also provide a test class:

public enum Language    {      Chinese,      English,      Japan,      Spanish,      Urdu    }

Obtain and bind the enumerated values:

 ViewBag.from_enum = Enum.GetValues(typeof(Language)).Cast<Language>();

View:

 @Html.DropDownList("database-dropdownlist", new SelectList(ViewBag.from_enum), new { @class = "btn btn-success dropdown-toggle form-control" })

Continue to see the results:

Enumeration bound to the drop-down box [3] (2)

Use the extension method @ Html. EnumDropDownListFor. The following two classes are provided for Demonstration:

Public class StudentModel {[Display (Name = "")] public ProgrammingLanguages Language {get; set ;}}
public enum ProgrammingLanguages  {    [Display(Name = "ASP.NET")]    ASPNet,    [Display(Name = "C# .NET")]    CSharp,    [Display(Name = "Java")]    Java,    [Display(Name = "Objective C")]    ObjectiveC,    [Display(Name = "Visual Basic .NET")]    VBNet,    [Display(Name = "Visual DataFlex")]    VisualDataFlex,    [Display(Name = "Visual Fortran")]    VisualFortran,    [Display(Name = "Visual FoxPro")]    VisualFoxPro,    [Display(Name = "Visual J++")]    VisualJPlus  }

Bind to the View:

  <div class="form-group">    @Html.LabelFor(model => model.Language, htmlAttributes: new { @class = "control-label col-md-2" })    <div class="col-md-10">      @Html.EnumDropDownListFor(model => model.Language, htmlAttributes: new { @class = "form-control" })      @Html.ValidationMessageFor(model => model.Language, "", new { @class = "text-danger" })    </div>  </div>

Let's look at the results.

If the drop-down box is selected, the other drop-down box changes accordingly. [4]

The most suitable example is the case selected by the province and city. Let's take a look.

(1) employees at the provincial and municipal levels.

public class Province  {    public int provinceId { get; set; }    public string provinceName { get; set; }    public string Abbr { get; set; }  }
public class City  {    public int CityId { get; set; }    public string CityName { get; set; }    public int provinceId { get; set; }  }
Public class Employees {[Key] public int EmployeeId {get; set;} [Required, Display (Name = "employee Name")] public string EmployeeName {get; set ;} [Required, Display (Name = "Address")] public String Address {get; set;} [Required, Display (Name = "")] public int Province {get; set;} [Required, Display (Name = "City")] public int City {get; set;} [Display (Name = "Region Code")] public String ZipCode {get; set;} [Required, Display (Name = "contact number")] public String Phone {get; set ;}}

(2) initialize data

List <Province> provinceList = new List <Province> () {new Province () {provinceId = 1, provinceName = "Hunan", Abbr = "hunan_province"}, new Province () {provinceId = 2, provinceName = "Guangdong", Abbr = "guangdong_province"}, new Province () {provinceId = 3, provinceName = "Jilin", Abbr = "jilin_province "}, new Province () {provinceId = 4, provinceName = "Heilongjiang", Abbr = "heilongjiang_province "}};

And how to bind ViewBag to the drop-down box and controller:

[HttpGet] public ActionResult Create () {ViewBag. provinceList = provinceList; var model = new Employees (); return View (model);} [HttpPost] public ActionResult Create (Employees model) {if (ModelState. isValid) {} ViewBag. provinceList = provinceList; return View (model);} public ActionResult FillCity (int provinceId) {var cities = new List <City> () {new City () {CityId = 10, cityName = "Yueyang City", provinceId = 1}, new City () {CityId = 10, CityName = "Shenzhen City", provinceId = 2}, new City () {CityId = 10, cityName = "Jilin City", provinceId = 3}, new City () {CityId = 10, CityName = "Harbin City", provinceId = 4}; cities = cities. where (s => s. provinceId = provinceId ). toList (); return Json (cities, JsonRequestBehavior. allowGet );}

(3) view display
 

@ Using (Html. beginForm () {@ Html. antiForgeryToken () <div class = "form-horizontal"> 

(4) Select the script from the province drop-down list to the city drop-down list.

function FillCity() {      var provinceId = $('#Province').val();      $.ajax({        url: '/Home/FillCity',        type: "GET",        dataType: "JSON",        data: { provinceId: provinceId },        success: function (cities) {          $("#City").html("");          $.each(cities, function (i, city) {            $("#City").append(              $('<option></option>').val(city.CityId).html(city.CityName));          });        }      });    }

Let's take a look at the entire process:

Conclusion

The drop-down box Binding is basically all covered. The above is all the content in this article. I hope it will be helpful for everyone's learning, and I hope you can support the help house a lot.

Related Article

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.