简体   繁体   English

下载MVC

[英]Dropdown in MVC

In my MVC application, I need to add a dropdown that would show a list of domain names. 在我的MVC应用程序中,我需要添加一个显示域名列表的下拉列表。

I already have a ViewModel that contains multiple properties. 我已经有一个包含多个属性的ViewModel。 I am not sure what the sequence of the steps should be: 我不确定步骤的顺序应该是什么:

  1. Add a new property to my ViewModel ? 将新属性添加到我的ViewModel What should be the type? 应该是什么类型? List? 名单?
  2. Define a method that populates the above property with values. 定义使用值填充上述属性的方法。
  3. Use that property in the View? 在视图中使用该属性? Use HTML.DropdownFor ? 使用HTML.DropdownFor

I know I should put some code in my Question, but right now I am having difficulty getting started with this... 我知道我应该在我的问题中加入一些代码,但是现在我很难开始这个...

EDIT: Added the following property to the ViewModel: 编辑:向ViewModel添加以下属性:

 public IEnumerable<SelectListItem> DomainList { get; set; }

and implemented a method to return a list of Domains: 并实现了一个返回域列表的方法:

internal static List<Domain> FetchAllDomains()

Next in my controller action, I have: 接下来在我的控制器动作中,我有:

var domains = FetchAllDomains().Select(d => d.DomainName);
return new EmailModel() {DomainList = domains };

But I get the following error: 但是我收到以下错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'. 无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'System.Collections.Generic.IEnumerable'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否错过了演员?)

1) Add a new property to my ViewModel? 1)向我的ViewModel添加一个新属性? What should be the type? 应该是什么类型? List? 名单?

You need 2 properties to be more precise: an IEnumerable<SelectListItem> to hold all the available options and a scalar property to hold the selected value 您需要2个属性才能更精确: IEnumerable<SelectListItem>用于保存所有可用选项,标量属性用于保存选定值

2) Define a method that populates the above property with values. 2)定义一个用值填充上述属性的方法。

Yes. 是。

3) Use that property in the View? 3)在视图中使用该属性? Use HTML.DropdownFor? 使用HTML.DropdownFor?

No, not in the view. 不,不在视图中。 The view doesn't call any methods. 视图不会调用任何方法。 A view works with the view model. 视图适用于视图模型。 It is the responsibility of the controller to pass a properly filled view model to the view. 控制器有责任将正确填充的视图模型传递给视图。

So for example: 例如:

public class MyViewModel
{
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }

    ... some other properties that your view might need
}

and then a controller action that will populate this view model: 然后是一个控制器动作,它将填充此视图模型:

public ActionResult Index()
{
    var model = new MyViewModel();
    model.Values = new[]
    {
        new SelectListItem { Value = "1", Text = "item 1" },
        new SelectListItem { Value = "2", Text = "item 2" },
        new SelectListItem { Value = "3", Text = "item 3" },
    };
    return View(model);
}

and finally the strongly typed view in which you will display the dropdown list: 最后是强类型视图,您将在其中显示下拉列表:

@model MyViewModel
@Html.DropDownListFor(x => x.SelectedValue, Model.Values)

UPDATE: 更新:

According to your updated question you are have an IEnumerable<SelectListItem> property on your view model to which you are trying to assign a value of type IEnumerable<string> which obviously is impossible. 根据您更新的问题,您在视图模型上有一个IEnumerable<SelectListItem>属性,您尝试为其指定IEnumerable<string>类型的值,这显然是不可能的。 You could convert this to an IEnumerable<SelectListItem> like this: 您可以将此转换为IEnumerable<SelectListItem>如下所示:

var domains = FetchAllDomains().Select(d => new SelectListItem
{
    Value = d.DomainName,
    Text = d.DomainName
});
return new EmailModel { DomainList = domains };

If you do not mind, I'll show you an example list of exams 如果您不介意,我会向您展示一个示例考试列表

public class SomeClass
{
    //Properties

    public int ExamId { get; set; }
    public SelectList ExamList { get; set; }
}

Helper: 帮手:

public static void PopulateExamList(MarkEditViewModel model,
    List<Exam> examList)
{
    model.ExamList = new SelectList(examList, "Id", "ExamName");
}

You must to add to marks, in my example, list of all exams. 在我的示例中,您必须添加所有考试的标记。 After this in View you will get a dropdown list of exams 在View中,您将获得一个考试下拉列表
And View (foreach every element in Model): 和View(预测模型中的每个元素):

@Html.DropDownListFor(model => model.ExamId,
                                        Model.ExamList,
                                        "Choose exam")

Once you have the list on your controller pass it to the view (as model or using ViewBag) and then use the helper: 一旦你的控制器上的列表将其传递给视图(作为模型或使用ViewBag),然后使用帮助器:

Html.DropDownList(
    string name,
    IEnumerable<SelectListItem> selectList,
    string optionLabel,
    object htmlAttributes) 

Or (MVC 3) 或者(MVC 3)

@Html.DropDownListFor(model => model.Property.ID,
    new SelectList(model.PropertyList, "ID", "Type"))

In your ViewModel 在您的ViewModel中

public class ViewModelClass
{
    public string DomainName { get; set; }

    public IEnumerable<SelectListItem> DomainList
    {
        get
        {
            return GetDomainNames()  //your method to get domain names
             .Select(d => new SelectListItem() { Text = d, Value = d });
        }
    }
}

your strongly typed view 你的强类型视图

@model ViewModelClass

@Html.DropDownListFor(model => model.DomainName, Model.DomainList)
  1. Yes you need a property in your model to handle the value of the DropDownList 是的,您需要模型中的属性来处理DropDownList的值
  2. Depends, normally could be an Integer that refers to the value of the DropDownlist The List that you're going to used to populate elements could be define as a element in a ViewBag, or an Another Attribute in your model 取决于,通常可以是指向DropDownlist的值的Integer。您将用于填充元素的List可以定义为ViewBag中的元素,或模型中的Another Attribute
  3. The razor Syntax depends entirely of the what do you try achieve you should use @Html.DropDownListFor() refers to an attribute of your model for guarantee that the view was stronglyTyped 剃刀语法完全取决于您尝试实现的内容应该使用@Html.DropDownListFor()引用模型的属性以保证视图是@Html.DropDownListFor()

You are in the right track, Have 2 properties in your ViewModel. 您处于正确的轨道,ViewModel中有2个属性。 One to hold the list of items and other for the selected Item Id from the UI 一个用于保存UI中所选项目ID的项目列表和其他项目

public class ProductViewModel
{
    public IEnumerable<SelectListItem> Items { get; set; }
    public string SelectedItemId { get; set; }
    //Other Properties
}

And in your Get Action method, Return the ViewModel with the data 在Get Action方法中,返回包含数据的ViewModel

 public ActionResult Index()
 {
    var objProduct = new ProductViewModel();
    objProduct.Items = new[]
    {
          new SelectListItem { Value = "1", Text = "Domain 1" },
          new SelectListItem { Value = "3", Text = "Domain 2" },
          new SelectListItem { Value = "3", Text = "Domain 3" }
    };
    // can replace the above line with loading data from Data access layer.
    return View(objProduct);
}

and in your view which is strongly typed to ProductViewModel 并在您的视图中强烈键入ProductViewModel

@model ProductViewModel
@using (Html.BeginForm())
{ 
  @Html.DropDownListFor(x => x.SelectedItemId, new SelectList(Model.Items,"Value","Text"), "Select..")
  <input type="submit" value="save" />
}

and in your HTTPpost Action, You will have the selected value available 在您的HTTPpost操作中,您将获得所选的值

[HttpPost]
public ActionResult Index(ProductViewModel model)
{
 //  check model.SElectedItemId here

}

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

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