我一直在閱讀有關這兩天的帖子,但仍然沒有找到答案。我想在我的ModelView中捕獲DropDownList選擇,將它傳遞給@ Html.ActionLink,它將把它發送回Controller中的特定Action。通過@ Html.DropDownList選擇使用@ Html.ActionLink與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 ,. ..)總是返回NULL到控制器? Model.SelectedShippingID不會使用DropDownList選定的id進行更新。請幫忙,因爲我在這裏耗盡時間。
您需要javascript/jquery根據所選值更改鏈接的URL,或者更好地使用表單(可以是FormMethod.Get)發佈該值。而它的原因是Razor代碼在發送到客戶端之前在服務器上進行評估,因此添加的路由值是「Model.SelectedShipmentID」的初始值(它不會因爲您在UI中選擇了某些內容而更改) –
並且由於'ShipmentID'是typeof'int',所以你的方法參數和模型屬性應該是'int?SelectedShippingID'(而不是'string') –
感謝你的快速回復。我正在通過選項工作,設法檢索SelectedShipmentID通過POST形式回到控制器上,在窗體上有60個字段,我會在下面看@ Stephen的建議,使用Ajax和局部視圖來減少不必要的數據交換,這是使用ActionLink的初衷。很多學習......很少的時間。 –