简体   繁体   English

ASP.NET MVC 3中的下拉列表

[英]Dropdown in ASP.NET MVC 3

I am new to MVC so probably confused . 我是MVC的新手,所以很困惑。 can somebody please explain me the dropdown in razor.my questions are- 有人可以向我解释一下razor中的下拉菜单吗?我的问题是-

  • What is the difference in dropdownlist and dropdownlistfor dropdownlist和dropdownlistfor有什么区别
  • how do i Pass ID column of my database table as value and NAME column as text. 如何将数据库表的ID列作为值传递,将NAME列作为文本传递。
  • How do i add "other" to the dropdownlist. 如何将“其他”添加到下拉列表中。
  • how do i access the selectedlistitem in code behind. 我如何在后面的代码中访问selectedlistitem。

if possible please explain with an example. 如果可能,请举例说明。

  1. DropDownList is generated by code like this: DropDownList由以下代码生成:

     @Html.DropDownList("PersonId", new SelectList(Model.People, "Id", "Text"); 

    On the other hand, DropDownListFor is generated like this: 另一方面,DropDownListFor生成如下:

     @Html.DropDownListFor(m => m.PersonId, new SelectList(Model.People, "Id", "Text") 
    Problem with DropDownList is that it has a magic string and if you decide to refactor the model later on, there's a high change you'll forget to change the magic string too. DropDownList的问题在于它具有一个魔术字符串,如果您以后决定重构模型,则有很大的变化,您也会忘记更改魔术字符串。

  2. You could do a LINQ query like this: 您可以这样执行LINQ查询:

     var datalist = New SelectList(from x in _peopleService select new SelectListItem { Text = x.Name, Value = x.Id}); 
    If you don't have a service or an ORM between it you need to apply it to your situation, but you can generate a list like that. 如果您之间没有服务或ORM,则需要将其应用于您的情况,但是可以生成类似的列表。

  3. After nr 2, you can 在nr 2之后,您可以

     datalist.Add(new SelectListItem() { Text = "Other", Value = "-1"}); 
    Also you have to put that datalist in your viewmodel/model that is passed to the View, so you can generate a selectlist item with that. 另外,您还必须将该数据列表放入传递给View的viewmodel / model中,以便可以生成一个selectlist项。 In this case you could just do: 在这种情况下,您可以执行以下操作:
     @Html.DropDownListFor(x => x.PersonId, Model.PersonList); 
    if you stored the list as PersonList in Model. 如果您将列表存储为Model中的PersonList。

  4. In your Viewmodel (Well, model in mvc) you have a property where the selected item will be stored, look at the 1st question - In this instance the selected item's id will be stored in the PersonId property. 在您的Viewmodel(好,mvc中的模型)中,您有一个属性,其中将存储所选项目,请看第一个问题-在这种情况下,所选项目的ID将存储在PersonId属性中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM