繁体   English   中英

MVC - 设置 SelectList 的选定值

[英]MVC - Set selected value of SelectList

在没有选择值的情况下实例化后,如何设置 SelectList 的 selectedvalue 属性;

SelectList selectList = new SelectList(items, "ID", "Name");

我需要在此阶段之后设置选定的值

如果您有 SelectList 对象,只需遍历其中的项目并设置您希望的项目的“Selected”属性。

foreach (var item in selectList.Items)
{
  if (item.Value == selectedValue)
  {
    item.Selected = true;
    break;
  }
}

或使用 Linq:

var selected = list.Where(x => x.Value == "selectedValue").First();
selected.Selected = true;

这里的聚会有点晚了,但这是多么简单:

ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82");

这使用我的方法 getcountries 来填充一个名为国家的模型,很明显,您可以将其替换为任何数据源、模型等,然后将 id 设置为选择列表中的值。 然后只需添加最后一个参数,在本例中为“82”以选择默认选定项。

[编辑] 以下是在 Razor 中使用它的方法:

@Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })

重要提示:另外,还有一件事需要注意,请确保用于存储下拉列表中所选 Id(在本例中为 model.CountryId)的模型字段可以为空,并且在第一次加载页面时设置为空。 这个每次都让我着迷。

希望这可以节省一些时间。

只需将第三个参数用于 mvc4 中的选定值

@Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974"))

这里选择“974” 指定值

在我的结果中选择的国家现在是 qatar.in C# 如下`

    foreach (CountryModel item in CountryModel.GetCountryList())
        {
            if (item.CountryPhoneCode.Trim() != "974")
            {
                countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });

            }
            else {


                countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });

            }
        }

为什么要在创建列表后尝试设置值? 我的猜测是您是在模型中而不是在视图中创建列表。 我建议在您的模型中创建底层可枚举,然后使用它来构建实际的 SelectList:

<%= Html.DropDownListFor(m => m.SomeValue, new SelectList(Model.ListOfValues, "Value", "Text", Model.SomeValue)) %>

这样你选择的值总是在视图渲染时设置,而不是在渲染之前设置。 此外,您不必在模型中放置任何不必要的 UI 类(即 SelectList),并且它可以保持不知道 UI。

对于@Womp 的回答,值得注意的是,可以删除“Where”,并且可以将谓词直接放入“First”调用中,如下所示:

list.First(x => x.Value == "selectedValue").Selected = true;

Doug 回答了我的问题...但我会解释我的问题究竟是什么,以及 Doug 如何帮助我解决您可能遇到的问题。

我调用 jquery $.post并用我的部分视图替换我的 div,就像这样。

function AddNewAddress (paramvalue) {
    $.post(url, { param: paramvalue}, function(d) {
        $('#myDiv').replaceWith(d);
    });
}

这样做时,出于某种原因,当我进入我的模型时,从未设置我选择的值附属属性,直到我进入它进入范围的视图。

所以,我之前所拥有的

@Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, Model.CustomerAddresses[i].YearsAtAddressSelectList, new {onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")"})

然而,即使 Model.CustomerAddresses[i].YearsAtAddressSelectList, 被设置......它也没有设置选定的值。

所以之后……

 @Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, new SelectList(Model.CustomerAddresses[i].YearsAtAddressSelectList, "Value", "Text", Model.CustomerAddresses[i].YearsAtAddress), new { onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")" })

奏效了!

我决定不使用DropDownListFor因为它在使用不显眼的验证时有问题,这就是为什么如果您对分类的类感到好奇,我会参考以下内容

HtmlExtensions.cs




[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */);

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, new RouteValueDictionary(htmlAttributes));

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes);

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */);

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, new RouteValueDictionary(htmlAttributes));

}


[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]

[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
{
    if (expression == null)
    {
        throw new ArgumentNullException("expression");
    }


    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);



    IDictionary<string, object> validationAttributes = htmlHelper
        .GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);



    if (htmlAttributes == null)
        htmlAttributes = validationAttributes;
    else
        htmlAttributes = htmlAttributes.Concat(validationAttributes).ToDictionary(k => k.Key, v => v.Value);



    return SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel, htmlAttributes);

}

您可以使用以下方法,这很简单。

new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault());

这将自动选择列表中的第一项。 您可以通过添加 where 子句来修改上述查询。

我在这里结束是因为 SelectListItem 不再正确选择选定的值。 为了修复它,我将 EditorFor 的用法更改为“手动”方法:

        <select id="Role" class="form-control">
            @foreach (var role in ViewBag.Roles)
            {
                if (Model.Roles.First().RoleId == role.Value)
                {
                    <option value="@role.Value" selected>@role.Text</option>
                }
                else
                {
                    <option value="@role.Value">@role.Text</option>
                }
            }
        </select>

希望它可以帮助某人。

我自己需要一个带有预选下拉值的可编辑网格中的下拉列表。 Afaik,选择列表数据由控制器提供给视图,因此它是在视图使用它之前创建的。 视图使用 SelectList 后,我​​将其交给使用标准 DropDownList 帮助程序的自定义帮助程序。 所以,一个相当轻的解决方案imo。 猜测它在撰写本文时符合 ASP.Net MVC 精神; 不开心的时候自己动手……

public static string DropDownListEx(this HtmlHelper helper, string name, SelectList selectList, object selectedValue)
{
    return helper.DropDownList(name, new SelectList(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectedValue));
}

我通常使用这种方法

        public static SelectList SetSelectedValue(SelectList list, string value)
    {
        if (value != null)
        {
            var selected = list.Where(x => x.Value == value).First();
            selected.Selected = true;
            return list;
        }
        return list;
    }

我希望下拉列表在操作方法中选择 id 的匹配值。 诀窍是在创建 SelectListItem 集合时设置 Selected 属性。 它不会以任何其他方式工作,也许我错过了一些东西,但最终,我的选择更优雅。

您可以编写任何返回布尔值的方法,以根据您的要求设置 Selected 值,在我的情况下,我使用了现有的 Equal 方法

public ActionResult History(long id)
        {
            var app = new AppLogic();
            var historyVM = new ActivityHistoryViewModel();

            historyVM.ProcessHistory = app.GetActivity(id);
            historyVM.Process = app.GetProcess(id);
            var processlist = app.GetProcessList();

            historyVM.ProcessList = from process in processlist
                                    select new SelectListItem
                                    {
                                        Text = process.ProcessName,
                                        Value = process.ID.ToString(),
                                        Selected = long.Equals(process.ID, id)                                    

                                    };

            var listitems = new List<SelectListItem>();

            return View(historyVM);
        }

下面的代码解决了两个问题:1)动态设置下拉列表的选定值,2)更重要的是为模型中的索引数组创建一个下拉列表。 这里的问题是每个人都使用选择列表的一个实例,即 ViewBoag.List,而数组需要每个下拉列表的一个 Selectlist 实例才能设置所选值。

在控制器中将 ViewBag 变量创建为 List(不是 SelectList)

//控制器代码
ViewBag.Role = db.LUT_Role.ToList();

//在视图中@Html.DropDownListFor(m => m.Contacts[i].Role, new SelectList(ViewBag.Role,"ID","Role",Model.Contacts[i].Role))

如果有人在看我重新发布我的答案: SelectListItem selected = true not working in view

在我自己寻找这个问题的答案之后 - 我一路上得到了一些提示,但这就是我的最终解决方案。 它是一个扩展方法。 我正在使用 MVC 5 C# 4.52 是目标。 下面的代码将选择设置为列表中的第一项,因为这是我需要的,您可能只想传递一个字符串并跳过枚举 - 但我也想确保我有一些东西从数据库返回到我的 SelectList)

Extension Method:

公共静态类 SelectListextensions {

public static System.Web.Mvc.SelectList SetSelectedValue

(这个 System.Web.Mvc.SelectList 列表,字符串值) { if (value != null) { var selected = list.Where(x => x.Text == value).FirstOrDefault(); selected.Selected = true;
} 返回列表; }
}

对于那些喜欢完全低调的人(像我一样),这里是用法。 对象类别有一个定义为名称的字段 - 该字段将在下拉列表中显示为文本。 您可以在上面的代码中看到对 Text 属性的测试。

Example Code:

SelectList categorylist = new SelectList(dbContext.Categories, "Id", "Name");

SetSelectedItemValue(categorylist);

select list function:

private SelectList SetSelectedItemValue(SelectList source) { Category category = new Category();

SelectListItem firstItem = new SelectListItem();

int selectListCount = -1;

if (source != null && source.Items != null)
{
    System.Collections.IEnumerator cenum = source.Items.GetEnumerator();

    while (cenum.MoveNext())
    {
        if (selectListCount == -1)
        {
            selectListCount = 0;
        }

        selectListCount += 1;

        category = (Category)cenum.Current;

        source.SetSelectedValue(category.Name);

        break;
    }
    if (selectListCount > 0)
    {
        foreach (SelectListItem item in source.Items)
        {
            if (item.Value == cenum.Current.ToString())
            {
                item.Selected = true;

                break;
            }
        }
    }
}
return source;

}

你可以把它变成一个通用的全包函数/扩展——但它对我来说是正常的

使用 LINQ 并在“选定”上添加条件作为问号条件。

    var listSiteId = (from site in db.GetSiteId().ToList()
                                      select new SelectListItem
                                      {
                                          Value = site.SITEID,
                                          Text = site.NAME,
                                          Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
                                      }).ToList();
                    ViewBag.SiteId = listSiteId;
这里有很多很好的答案,但也有很多不同的方法来做到这一点。 这是我的。

我认为这是所有“前端”DDL 代码(都在带有实体框架的 .NET MVC 中的 CSHTML 页面中——因此“Id”数据库引用,以及带有 jQ​​uery 前端验证的 Bootstrap 3 样式)。 我也提到“前端”,因为我没有显示任何模型注释或控制器/存储库/服务代码。

这是此 DDL 从中获取其值的 db 表:

在此处输入图片说明

它在 db 表中有一个默认值(“不适用”或 Id #4),这很烦人,但我不得不在现实世界中处理这个问题,所以希望这个例子有帮助。 我在这个页面上的原因是为了解决这样的情况,一旦我想起了如何去做,我想我会在这里发布我所做的以防对其他人有帮助,因为其他答案不是正是这样。

好的,这是在“创建”表单上执行的操作,您将在其中创建初始对象。 这就是为什么默认选择是 db 表中的 #4。

“创建”表单 DDL 示例

<div class="form-group">
    @Html.LabelFor(
      m => m.Survey.CountryId, 
      "North American Country you live in?", new 
@* .required is custom CSS class to add red asterisk after label *@
      { @class = "col-md-4 control-label required" }
    )
    <div class="col-md-8">
        @Html.DropDownListFor(
            m => m.Survey.CountryId,
            Model.Surveys.Select(i => new SelectListItem()
            {
                Value = i.Id.ToString(),
                Text = $"{i.Code} - {i.Description}",
/*  gave default selection of Id #4 in db table */
                Selected = i.Id == 4 ? true : false
            }), new
            {
                @class = "form-control",
                data_val = "true",
                data_val_required = "This is a required selection"
            })
        @Html.ValidationMessageFor(m => m.Survey.CountryId)
    </div>
</div>

“编辑”表单 DDL 示例


<div class="col-md-8">
    @Html.DropDownListFor(
        m => m.Survey.CountryId,
        Model.Surveys.Select(i => new SelectListItem()
        {
            Value = i.Id.ToString(),
            Text = $"{i.Code} - {i.Description}",
/* for Edit form, find the actual selected value the survey taker made */
            Selected = i.Id == Model.Survey.CountryId ? true : false
        }), new
        {
            @class = "form-control",
            data_val = "true",
            data_val_required = "This is a required selection"
        })
    @Html.ValidationMessageFor(m => m.Survey.CountryId)
</div>

你总是可以做一个这样的默认选择:

    @Html.DropDownListFor(
        m => m.Survey.CountryId,
        Model.Surveys.Select(i => new SelectListItem()
        {
            Value = i.Id.ToString(),
            Text = $"{i.Code} - {i.Description}",
            Selected = i.Id == Model.Survey.CountryId ? true : false
/* Add a default DDL selection when you're not trying to get it from a db */
        }), "-- select a country --", new
        {
            @class = "form-control"
        })

它应该是这样的:

此 DDL 用于“州”而不是“国家”,它有一个默认的“--选择--”选项,但更像是“编辑表单”版本,因为它已经被选中,现在显示从数据库中检索到的选项.

但除此之外...

在此处输入图片说明

暂无
暂无

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

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