我的目標是將記錄保存在與當前詳細視圖中的項目關聯的不同控制器中。我有一個詳細查看這個從不同的表,可以使用下面的代碼顯示的相關記錄列表:跨控制器傳遞參數
<table class="table">
<tr>
<th>
Date
</th>
<th>
Notes
</th>
<th>
Contractor
</th>
</tr>
@foreach (var item in Model.ServiceHistories)
{
<tr>
<td width="200px">
@Html.DisplayFor(modelItem => item.Date)
</td>
<td>
@Html.DisplayFor(modelItem => item.Notes)
</td>
<td>
@Html.DisplayFor(modelItem => item.ContractorID)
</td>
</tr>
}
@Html.ActionLink("Create", "Create", "ServiceHistories", new { id = Model.AssetID }, null)
</table>
在我已經在不同的控制器中添加一個動作鏈接到一個動作底部創建一個新的服務歷史通過傳入該資產的AssetID來記錄該資產。這是服務歷史的創建(POST和GET)行動:
// GET: ServiceHistories/Create
public ActionResult Create(int? id)
{
ViewBag.AssetID = id;
return View();
}
// POST: ServiceHistories/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ServiceID,AssetID,Date,ContractorID,Notes")] ServiceHistory serviceHistory)
{
if (ModelState.IsValid)
{
db.ServiceHistories.Add(serviceHistory);
db.SaveChanges();
return RedirectToAction("Details", "Assets", new { id = serviceHistory.AssetID });
}
ViewBag.AssetID = new SelectList(db.Assets, "AssetID", "Description", serviceHistory.AssetID);
return View();
}
我加入(INT標識)作爲參數,以創建行動,並賦予它ViewBg.AssetID whic被傳遞到視圖OK因爲我可以在頁面上顯示它。我的問題是
我的第一個問題是我如何使用這個值來替換下面的代碼。即我想隱藏AssetID字段並改爲使用參數ViewBag.AssetID。
<div class="form-group">
@Html.LabelFor(model => model.AssetID, "AssetID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("AssetID", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.AssetID, "", new { @class = "text-danger" })
</div>
</div>
我已經試過
@Html.HiddenFor(ViewBag.AssetID)
但我不能得到它的編譯錯誤:
編譯器錯誤信息:CS1973: 'System.Web.Mvc.HtmlHelper' 有一個名爲沒有適用的方法'隱藏',但似乎有一個名稱的擴展方法。擴展方法不能動態分派。考慮轉換動態參數或調用擴展方法而不使用擴展方法語法。
我已經閱讀了接近這個帖子和教程的負載,但我似乎能夠破解我做錯了什麼。
任何幫助,將不勝感激。
你可以使用'@ Html.Hidden(ViewBag.AssetID)',但我將發佈備選答案 – 2014-09-23 03:42:58