2013-01-31 22 views
5

如何將現有視圖附加到操作? 我的意思是,我已經將這個非常看法附加到一個動作,但我想要附加到第二個動作。如何將現有視圖附加到控制器操作?

例如: 我有一個名爲索引的行爲和一個視圖,同名的附加到它,右鍵單擊,添加視圖...,但現在,如何附加到第二個?假設一個名爲Index2的Action,該如何實現?

下面的代碼:

//this Action has Index View attached 
public ActionResult Index(int? EntryId) 
{ 
    Entry entry = Entry.GetNext(EntryId); 

    return View(entry); 
} 

//I want this view Attached to the Index view... 
[HttpPost] 
public ActionResult Rewind(Entry entry)//...so the model will not be null 
{ 
    //Code here 

    return View(entry); 
} 

我GOOGLE了它,並不能找到一個合適的答案...... 這是可能的嗎?

回答

5

你不能「附加」行動的意見,但你可以通過使用Controller.View方法

public ActionResult MyView() { 
    return View(); //this will return MyView.cshtml 
} 
public ActionResult TestJsonContent() { 
    return View("anotherView"); 
} 

http://msdn.microsoft.com/en-us/library/dd460331%28v=vs.98%29.aspx

+0

當我用鼠標右鍵單擊操作的上下文菜單顯示我添加視圖選項,沒關係。所以我不能添加這個相同的視圖到另一個行動? –

+0

您可以手動添加一個新的視圖到您的項目,然後用上面的代碼 –

+0

我不想增加一個新的觀點,我想重複使用名稱不同,其他動作現有的View返回它... –

4

這是否幫助定義視圖要通過一個操作方法返回什麼?您可以使用View的過載,指定了不同的看法:

public class TestController : Controller 
{ 
    // 
    // GET: /Test/ 

    public ActionResult Index() 
    { 
     ViewBag.Message = "Hello I'm Mr. Index"; 

     return View(); 
    } 


    // 
    // GET: /Test/Index2 
    public ActionResult Index2() 
    { 
     ViewBag.Message = "Hello I'm not Mr. Index, but I get that a lot"; 

     return View("Index"); 
    } 


} 

這裏查看(Index.cshtml):

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<p>@ViewBag.Message</p> 
+1

在你的例子中它將返回View(「Index」,entry); –

+0

實際上,不是......我需要將模型作爲參數傳遞給動作。 –

+1

我的意思是你可以在代碼中使用'return View(「Index」,entry)替換'code here','return View(entry) –

相關問題