简体   繁体   English

将下拉列表中的值分配给视图中 Razor 页面中的变量

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

Is it possible to get the value from a dropdown field and store it as a variable in the same View?是否可以从下拉字段中获取值并将其作为变量存储在同一个视图中?

I have this dropdown我有这个下拉菜单

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

and I would like to get the value from the select to store as a variable to use in the next dropdown something like this:我想从选择中获取值以存储为变量以在下一个下拉列表中使用,如下所示:

@{ 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>

Or is there a different way to go about this?或者有什么不同的方法来解决这个问题?

Razor code is compiled on the server, so all variables are set before it's delivered to the browser. Razor 代码是在服务器上编译的,因此所有变量在传递到浏览器之前都已设置。 The Razor code doesn't know what value will be selected in the first dropdown to populate the second one. Razor 代码不知道将在第一个下拉列表中选择什么值来填充第二个。

What you would need to do is use a Javascript onchange event to perform an AJAX call and retrieve the data you need based on the first dropdown, to populate the second dropdown.您需要做的是使用 Javascript onchange事件来执行 AJAX 调用并根据第一个下拉列表检索您需要的数据,以填充第二个下拉列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM