【问题标题】:How can I pass the URL value into my combobox?如何将 URL 值传递到我的组合框中?
【发布时间】:2021-10-27 21:06:40
【问题描述】:

我有以下网址:https://localhost:27635/Student/Create?PersonId=1

我还有一个组合框,里面装满了用户,用户可以使用它来选择一个人。如何将组合框设置为默认具有来自 URL 的 PersonId?

这是组合框代码:

@Html.DropDownListFor(
    x => x.PersonId,
    new SelectList(Model.Persons, "Id", "Fullname", Model.PersonId),
    "-- Select --", new { @class = "form-control" }
)

它包含 PersonIds,显示全名。 我想使用组合框而不是直接从 URL 保存值的原因是因为我想允许用户更改。

我好奇的另一件事是,如果 URL id 不正确且不在组合框中,是否有可能显示默认 -- Select --

谢谢

【问题讨论】:

    标签: c# html parameters model dropdownlistfor


    【解决方案1】:

    你好,你可以正确使用following post之类的东西

    基本上SelectList 函数有一个重载,您可以在this link 中找到它

    所以SelectList 会关注

    items (IEnumerable) - 用于构建列表中每个 SelectListItem 的项目。

    dataValueField (String) - 数据值字段。用于匹配对应SelectListItemValue属性。

    dataTextField (String) - 数据文本字段。用于匹配对应SelectListItemText属性。

    dataGroupField (String) - 数据组字段。用于匹配对应SelectListItemGroup属性。

    selectedValue (Object) - 选定的值。用于匹配对应SelectListItemSelected属性。

    这是一个例子:

        @Html.DropDownListFor(
        m => m.CountryId, // Specifies where to store selected country Id
                          // It needs to be null for the default selection to work!
    
        new SelectList(Model.Countries, // IEnumerable<Country>, contains all countries loaded from a database
                       "Id",   // Use Country.Id as a data source for the values of dropdown items
                       "Name", // Use Country.Name as a data source for the text of dropdown items
                       13 // Specifies Australia (which has ID of 13) as the element selected by default
                       ),
    
        // Text of option that prompts user to select
        "- Please select your country -"
    )
    

    【讨论】:

    • 您可以将默认值替换为 Request.QueryString["PersonId"]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多