2012-07-02 35 views
1

我有一個對象視圖,包含該視圖上的數據和按鈕。用戶可以查看對象信息並單擊該按鈕以轉到新的查看錶單,以便他可以輸入信息來創建項目。我的挑戰是,我如何將對象的ID附加到先前的視圖上,以將它與它們創建和提交的信息相關聯並附加到它們上面?MVC3 actionlink將ID附加到對象

+0

可以顯示一些代碼?這將有助於解決這個問題 –

+0

我現在從我的iPad發送,所以現在不在話下。你知道一個很好的解決方案來適應這個概念嗎? –

回答

1
@Html.ActionLink("Add","AddNotes","Object",new {@id=5},null) 

這將創造e帶有查詢字符串?id=5的標籤。 (您可以使用視圖中的動態值替換硬編碼5)

有一個屬性可以爲創建表單保留​​3210的值。

public class CreateNoteViewModel 
{ 
    public int ParentId { set;get;} 
    public string Note { set;get;} 
    //Other properties also 
} 

在您的GET閱讀本action方法,創建第二視圖,設置視圖模型/型號的該屬性的值。

public ActionResult AddNotes(int id) 
{ 
    var model=new CreateNoteViewModel(); 
    model.ParentId=id; 
    return View(model); 
} 

而在您的強類型視圖中,請將此值保存在隱藏變量中。

@model CreateNoteViewModel 
@using(Html.BeginForm()) 
{ 
@Html.TextBoxFor(Model.Note) 
@Html.HiddenFor(Model.ParentId) 
<input type="submit" /> 
} 

現在,在您HttpPost動作,你可以從您發佈的模型的ParentId屬性來獲取對象ID

[HttpPost] 
public ActionResult AddNotes(CreateNoteViewModel model) 
{ 
if(ModelState.IsValid() 
{ 
    //check for model.ParentId here 
    // Save and redirect 
} 
return View(model); 
} 
+0

我正在研究此解決方案。如果我成功了,我會感謝你的回答。感謝代碼。 (: –

+0

它是否有關係,不管它是否設置;得到;或得到;設置;我已得到;設置; –

+0

@HelloJonnyOh:那個順序沒有關係 – Shyju

0

您可以使用隱藏輸入& viewdata,PSEUDOCODE。 注意您可能不得不使用字符串查看數據並將其轉換回您的控制器中的ID。有關ViewData/ViewBag(和缺點)的基本說明,請參閱this link

您需要將數據傳遞到第一個操作的視圖(控制器) Controller基類有一個「ViewData」字典屬性,可用於填充要傳遞給View的數據。使用鍵/值模式將對象添加到ViewData字典中。

控制器

public ActionResult yourfirstaction() 
     { 
      //assign and pass the key/value to the view using viewdata 
      ViewData["somethingid"] = ActualPropertyId; 

鑑於 - 獲取的價值用它來與隱藏的輸入回傳給下一個控制器來呈現下一個視圖

<input type="hidden" name="somethingid" value='@ViewData["somethingid"]' id="somethingid" /> 

控制器

public ActionResult yournextaction(string somethingid) 
     { 
      //use the id 
      int ActualPropertyId = Convert.ToInt32(somethingid); 
+0

我會在哪裏放置隱藏的輸入?我假定用戶來自的頁面... –

+0

是的,在您的視圖中,您的按鈕正下方。 – user1166147

+0

我想要傳遞的屬性的實際名稱應該放在哪裏?你可以編輯你的僞代碼並替換爲「ActualPropertyId」? –