【问题标题】:How to preselect MVC Dropdownlistfor?如何预选 MVC Dropdownlistfor?
【发布时间】:2023-03-06 15:01:01
【问题描述】:

我在一个页面上有多个在运行时构建的下拉列表。我有一个带有选择列表的视图模型。我试过this post,这很棒,但有点不同,因为我在视图上有一组视图模型。我想我很接近,但我不确定如何正确使用 DropDownListFor。如何预先选择具有不同值的每个下拉列表?

虚拟机

public class categoryVm
{        
    public IEnumerable<SelectListItem> category { get; set; }

    public string SelectedValue { get; set; }
} 

查看

@model IEnumerable<categoryVm>
@foreach (var item in Model)
{
   //i think i am missing something here???
   @Html.DropDownListFor(**x => item.SelectedValue**, item.category)
}

控制器

name 是 StaticName 之一,它就像一个 Id,它在列表中。

var categories = new List<categoryVm>();
var selectlistcolumns = columns.Select(x => new SelectListItem
            {                    
                Value = x.StaticName,
                Text = x.DisplayName
            });

foreach (var column_loopVariable in dtCSV.Columns)
            {
                var category= new categoryVm();                    
                category.category= selectlistcolumns;
                category.SelectedValue = "name";
                categories .Add(category);
            }
     return View(categories);

我更喜欢 mvc 解决方案而不是使用 javascript 更改 dom。

【问题讨论】:

  • 您可以像预填充 TextBox 值一样预选 DDL 值。有意义吗?

标签: c# asp.net asp.net-mvc html.dropdownlistfor


【解决方案1】:

试试这个

var selectlistcolumns = columns.Select(x => new SelectListItem
        {                    
            Value = x.StaticName,
            Text = x.DisplayName,
            Selected = x.DisplayName == "name"  // this sets the selected value
        });

foreach (var column_loopVariable in dtCSV.Columns)
        {
            var category= new categoryVm();                    
            category.category= selectlistcolumns;
            //category.SelectedValue = "name"; // not required
            categories .Add(category);
        }

另外,如果您注意到Html.DropDownListFor(propExpresstion, selectList) 的签名 因此,您假设的第一个参数不会设置所选值。希望这会有所帮助!

【讨论】:

    【解决方案2】:

    由于您的控制器返回列表。 您应该在视图页面中使用 IList 而不是 IEnumerable。

    @model IList<categoryVm>
    
    for (int i = 0; i < Model.Count; i++) 
    {
       @Html.DropDownListFor(m => Model[i].SelectedValue, Model[i].category)
    }
    

    View Model IEnumerable<> property is coming back null (not binding) from post method?

    【讨论】:

    • 这个方法,或者另一个选项是为“categoryvm”创建一个EditorTemplate,在这种情况下你可以简单地调用Html.EditorFor,MVC会自动为你的字段应用正确的索引
    【解决方案3】:
    @Html.DropDownListFor(m => item.SelectedValue, new SelectList(item.category))
    

    【讨论】:

    • 感谢您的回复 Murali。 m => item.category 在智能感知中没有 SelectedValue .. m => item 有 SelectedValue 但这不起作用。
    • @LaurenceNyein,这是我的错误。编辑答案。
    • 感谢您的帮助,但我看不出与我的原始代码有什么不同......请您再解释一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2019-11-20
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多