簡體   English   中英

ASP.Net Core C# Select 選項重定向更改選定選項

[英]ASP.Net Core C# Select Option Redirect Change Selected Option

我已經能夠在我很滿意的 ASP.Net Core 應用程序中按名稱和價格對升序和降序進行排序。 我正在使用 HTML select 並將選項返回給 Controller ,它工作得很好。 我唯一的抱怨是,每次單擊其中一個選項時,它仍然默認為第一個選項:

<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 實現我想要的,因為它沒有在 URL 中注冊?order=name_desc等.

提前感謝您的幫助!

selectonchange事件中,您可以將選定的索引傳遞給操作:

<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>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM