首页 > 解决方案 > ASP.Net Core C# 选择选项重定向更改选择的选项

问题描述

我已经能够在我很满意的 ASP.Net Core 应用程序中按名称和价格对升序和降序进行排序。我正在使用 HTML 选择并将选项返回给完美运行的控制器。 我唯一的抱怨是,每次单击其中一个选项时,它仍然默认为第一个选项:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
            <option value="@Url.Action("Spain", new {order="name"})">
                Name Ascending (A-Z)
            </option>
            <option value="@Url.Action("Spain", new {order="name_desc"})">
                Name Descending (Z-A)
            </option>
            <option value="@Url.Action("Spain", new {order="price"})">
                Price Ascending (€)
            </option>
            <option value="@Url.Action("Spain", new {order="price_desc"})">
                Price Descending (€)
            </option>
        </select>

我希望它将页面加载时的选定选项更改为我刚刚选择的对对象进行排序的选项。我知道这很复杂,因为我在技术上重定向到一个新页面,但我似乎无法使用 jQuery 甚至基本 JS 实现我想要的,因为它没有?order=name_desc在 URL 中注册等。

提前感谢您的帮助!

标签: javascriptc#jqueryhtmlasp.net-core

解决方案


如果您可以将选定onchangeselect索引传递给操作:

<select id="select1" onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value+'&selectedIndex='+this.options[this.selectedIndex].index);">

在行动中,从查询字符串中获取索引,使用 Viewbag 发送到视图:

public ActionResult Spain(string order ,string selectedIndex)       
{
    ....
    ViewBag.selectedIndex = selectedIndex;
    return View();
}   

在该页面中,加载 DOM 后,您可以使用 JQuery 设置选定的索引值:

@section Scripts{ 
    <script>
        $(function () {            
            if (@ViewBag.selectedIndex !=null) {
                $("#select1").prop('selectedIndex', @ViewBag.selectedIndex);
            }

        })
    </script>
}

推荐阅读