使用@ Html.ActionLink和ViewModel到Controller传递@ Html.DropDownList选择

时间:2015-08-26 02:00:06

标签: asp.net-mvc-5 html.dropdownlistfor html.actionlink

我已经阅读了两天有关此事的帖子,但仍然没有找到答案。我想在我的ModelView中捕获DropDownList选项,将其传递给@ Html.ActionLink,它将把它发送回Controller中的特定Action。

我的ViewModel:

    public class ViewModelShipments
    {
        public ViewModelShipments()
        {
            tblShipments = new tblShipments();
        }
        public tblShipments tblShipments;
        public IEnumerable<SelectListItem> ShipmentIDsList;
        public string SelectedShipmentID; 
    }

我的控制器:

public ActionResult SelShipment(string SelectedShipmentID)//for ShipmentID change via DropDownList
        {
            int id = db.tblShipments.Max(p => p.ShipmentID); // find last ShipmentID
            if (SelectedShipmentID != null)
            {
                id = Int32.Parse(SelectedShipmentID);//convert text to int
            }

我的观点:

            @Html.DropDownListFor(expression: model=>model.SelectedShipmentID,selectList: Model.ShipmentIDsList) @* render DropDownList object*@
            @Model.SelectedShipmentID @* display value of SelectedShipmentID *@

            <!-- Upon Click, send selected ID to controller --> 
            <!-- the ActionLink is working, but the routeValues: always contain NULL -->
            @Html.ActionLink(linkText: "Submit", actionName: "SelShipment", controllerName: "Shipment", routeValues: Model.SelectedShipmentID, htmlAttributes: null)

为什么ActionLink(...,routeValues:Model.SelectedShipmentID,...)总是向Controller返回NULL? Model.SelectedShipmentID未使用DropDownList选择的id更新。请帮忙,因为我已经没时间了。

1 个答案:

答案 0 :(得分:1)

Razor代码在发送到视图之前在服务器上进行解析,因此route参数的值将是HttpURLConnection的初始值。从下拉列表中选择值不会更改您已呈现的网址。

您可以使用javascript / jquery来处理下拉列表的SelectedShipmentID事件(或链接.change()事件)来更新网址,但是处理此问题的更好方法是使用一个表单获取控制器方法

.click()

请注意@model ViewModelShipments @using (Html.BeginForm("SelShipment", "Shipment", FormMethod.Get)) { @Html.DropDownListFor(m => m.SelectedShipmentID, Model.ShipmentIDsList, "-Please select-") <input type="submit" /> } 的最后一个参数添加标签选项,以便您回发DropDownListFor(),但不确定这是否适合您。

由于您绑定的值为null,因此您的模型属性和方法参数都应为int而不是int?。此外,您应该更改控制器中的逻辑,以便在将有效值传递给方法时不进行不必要的数据库调用。

string

旁注:从您的视图模型属性中,我假设您要根据所选public ActionResult SelShipment(int? SelectedShipmentID) { if (!SelectedShipmentID.HasValue) { // only necessary to call database if SelectedShipmentID is null SelectedShipmentID = db.tblShipments.Max(p => p.ShipmentID) } .... } 的值在视图中显示一些数据。如果是这样,您应该考虑使用ajax将所选值发布到控制器方法,该方法根据值返回ShipmentID数据,作为部分视图或json,并更新当前页面,而不是完成页面刷新每次。