簡體   English   中英

將下拉列表中的值分配給視圖中 Razor 頁面中的變量

[英]Assign value from dropdown to a variable in Razor pages in view

是否可以從下拉字段中獲取值並將其作為變量存儲在同一個視圖中?

我有這個下拉菜單

   <label for="vehicleMake">Choose your car's make:</label>

   <select id="vehicleMake" name="VehicleMake">
       @foreach (var item in Model.Cars)
       {
           if (@item.Category == 1072)
           {
               <option value="@item.UniqueId">@item.Description</option>

           }
       }
   </select>

我想從選擇中獲取值以存儲為變量以在下一個下拉列表中使用,如下所示:

@{ var selectedVehicleMake = @*????? get the value from the previous dropdown ?????*@
}

    <label for="vehicleModel">Choose your car's model:</label> 
    <select id="vehicleModel" name="VehicleModel">
        @foreach (var item in Model.Cars)
        {
            if (@item.Category == 1073 && @item.VehicleMakeId == selectedVehicleMake)
            {
                <option value="@item.UniqueId">@item.Description</option>

            }
        }
     </select>

或者有什么不同的方法來解決這個問題?

Razor 代碼是在服務器上編譯的,因此所有變量在傳遞到瀏覽器之前都已設置。 Razor 代碼不知道將在第一個下拉列表中選擇什么值來填充第二個。

您需要做的是使用 Javascript onchange事件來執行 AJAX 調用並根據第一個下拉列表檢索您需要的數據,以填充第二個下拉列表。

暫無
暫無

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

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