未在下拉列表中设置所选值

Selected value not being set in dropdown list

几天前我问了一个类似的问题,但没有提到我的页面上有第二个下拉列表。第一个列表使用 Html.DropDownList,我的第二个列表使用 select 语句。

我能够使用我提供的解决方案将重新发布的 selected 项目渲染到第一个下拉列表 (SelectedItem)。但是当我尝试将相同的技术应用于我的第二个下拉列表 (SortSelect) 时,它失败了。

我不明白为什么,因为它们都是由 id 标识的,而且我使用相同的 ViewBag 语句将我想要显示的数据发送回视图。我的第二个下拉列表有什么问题导致 selected 项无法呈现?

对于无法建立连接并解决本质上相同问题的第二次迭代,我提前表示歉意。我是 .Net 的新手,仍在学习基础知识。

我的观点

// This is the first dropdown list
@Html.DropDownList("SelectedItem", Model.ReverseMonthsLists(),
    new { @onchange = "CallChangeFunction(this.value)" })

// This is the second dropdown list 
<select id="SortSelect" onchange="CallChangeFunction(value)">
    <option value="default">Default</option>
    <option value="make">Make</option>
    <option value="model">Model</option>
    <option value="year">Year</option>
</select>

// This is my javascript
@section scripts
{
    <script>
        function CallChangeFunction() {
            var dateItem = document.getElementById("SelectedItem").value;
            var sortItem = document.getElementById("SortSelect").value;
            window.location.href = "/dashboard/Report_Performance?dateItem=" + dateItem + "&sortItem=" + sortItem;
            }
    </script>
}

我的控制器

public ActionResult Report_Performance(string dateItem, string sortItem)
{
    DateTime newDate = DateTime.Now.Date.AddMonths(-1);
    if (dateItem != null && dateItem != "")
        newDate = DateTime.Parse(dateItem);
    var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, newDate);

    if (sortItem == "make")
        aVar.CurrentListingStats = aVar.CurrentListingStats.OrderBy(i => i.Make).ToList();
    else if (sortItem == "model")
        aVar.CurrentListingStats = aVar.CurrentListingStats.OrderBy(i => i.Model).ToList();
    else if (sortItem == "year")
        aVar.CurrentListingStats = aVar.CurrentListingStats.OrderBy(i => i.Year).ToList();

    ViewBag.SelectedItem = dateItem;  //<- THIS ONE WORKS FINE
    ViewBag.SortSelect = sortItem;    //<- THIS IS NOT WORKING, IT'S IGNORED BY THE VIEW

    return this.View(aVar);
}

好的,您的第二个下拉列表是标准的 HTML,因此您必须为 'set' 所选值编写更多代码。忽略第一个列表和 JS 方法(它们可以保持原样)你可以试试这个:

查看

@{
   string _sortItem = ViewBag.SortSelect == null ? "" : ViewBag.SortSelect;
}
...

<select id="SortSelect" onchange="CallChangeFunction(value)">
    <option value="default" @(_sortItem=="default" ? Html.Raw("selected") : Html.Raw(""))>Default</option>
    <option value="make" @(_sortItem=="make" ? Html.Raw("selected") : Html.Raw(""))>Make</option>
    <option value="model" @(_sortItem=="model" ? Html.Raw("selected") : Html.Raw(""))>Model</option>
    <option value="year" @(_sortItem=="year" ? Html.Raw("selected") : Html.Raw(""))>Year</option>
</select>

...

老实说,我会让它更动态(像其他列表一样)并从控制器(通过 ViewBag)提供列表值,然后在视图中也为它使用 @Html.DropDownList(...