【发布时间】:2015-08-26 02:00:05
【问题描述】:
我已经阅读了两天有关此的帖子,但仍然没有找到答案。我想在我的 ModelView 中捕获 DropDownList 选择,将其传递给 @Html.ActionLink,后者会将其发送回 Controller 中的特定 Action。
我的视图模型:
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,...) 总是返回 NULL 给 Controller ? Model.SelectedShipmentID 不会使用 DropDownList 选择的 id 进行更新。请帮忙,因为我的时间不多了。
【问题讨论】:
-
您需要 javascript/jquery 根据所选值更改链接的 url,或者最好使用表单(可以是
FormMethod.Get)发布值。其 null 的原因是 Razor 代码在发送到客户端之前在服务器上进行评估,因此添加的路由值是Model.SelectedShipmentID的初始值(它不会因为您在 UI 中选择某些内容而改变 -
因为
ShipmentID是int类型,所以你的方法参数和模型属性应该是int? SelectedShipmentID(不是string) -
感谢您的快速回复。我正在研究这些选项。已设法通过将表单发送回控制器来检索 SelectedShipmentID。表单上有 60 个字段,我将在下面查看 @Stephen 的建议,即使用 Ajax 和部分视图来最大程度地减少不必要的数据交换。这是使用 ActionLink 的初衷。要学的东西太多了……时间太少了。
标签: asp.net-mvc-5 html.dropdownlistfor html.actionlink