2014-09-23 106 views
0

我的目標是將記錄保存在與當前詳細視圖中的項目關聯的不同控制器中。我有一個詳細查看這個從不同的表,可以使用下面的代碼顯示的相關記錄列表:跨控制器傳遞參數

<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' 有一個名爲沒有適用的方法'隱藏',但似乎有一個名稱的擴展方法。擴展方法不能動態分派。考慮轉換動態參數或調用擴展方法而不使用擴展方法語法。

我已經閱讀了接近這個帖子和教程的負載,但我似乎能夠破解我做錯了什麼。

任何幫助,將不勝感激。

+0

你可以使用'@ Html.Hidden(ViewBag.AssetID)',但我將發佈備選答案 – 2014-09-23 03:42:58

回答

1

不知道爲什麼你會把它分配到ViewBag,因爲你的型號ServiceHistory有一個屬性AssetID

控制器

public ActionResult Create(int? id) 
{ 
    ServiceHistory model = new ServiceHistory(); 
    model.AssetID = id; 
    return View(model); 
} 

查看

@model YourAssembly.ServiceHistory 
.... 
@Html.HiddenFor(m => m.AssetID) 
+1

感謝。輕微的mod是改變ServiceHistories模型=新的ServiceHistories(); ServiceHistory model = new ServiceHistory();我認爲這是因爲我們只傳遞一個記錄。 – Spionred 2014-09-23 04:11:51

+0

當然 - 我會更新答案 – 2014-09-23 04:15:26