2014-09-20 46 views
0

我有這樣的控制器:Html.Action錯誤的行爲

public class PostController : Controller 
{ 
    public ActionResult SimplePost(PostData postData, bool isRichView = true) 
    { 
     ViewBag.IsRichView = isRichView; 
     return View(postData); 
    } 

    public ActionResult VideoPost(PostData postData, bool isRichView = true) 
    { 
     ViewBag.IsRichView = isRichView; 
     return View(postData); 
    } 

    public ActionResult Post(PostData postData, bool isRichView = true) 
    { 
     switch (postData.PostType) 
     { 
      case PostType.SimplePost: 
       return SimplePost(postData, isRichView); 
      case PostType.VideoPost: 
       return VideoPost(postData, isRichView); 
      default: 
       throw new InvalidDataException("There is no post shell for this kind of post!"); 
     } 
    } 
} 

而在其他地方,我把它叫做:

foreach (var postData in RepositoryManager.PostRepository.GetList()) 
{ 
    @Html.Action("Post", "Post", new {postData}) //Call Post method 
} 

所以之後,我得到錯誤: 找不到視圖「後「或樣本,或者沒有處理程序視圖不支持搜索。搜索在以下位置 :

~/Views/Post/Post.aspx 
~/Views/Post/Post.ascx 
~/Views/Shared/Post.aspx 
~/Views/Shared/Post.ascx 
~/Views/Post/Post.cshtml 
~/Views/Post/Post.vbhtml 
~/Views/Shared/Post.cshtml 
~/Views/Shared/Post.vbhtml 

(大約從我的語言的英語翻譯)。

但爲什麼會發生?

我從SimplePost和VideoPost方法調用View,爲什麼它會試圖找到「Post」視圖?

回答

1

MVC知道動作Post正在排除。當你像一個方法一樣執行動作時,它不會改變任何東西,就像這段代碼在Post動作中一樣。 MVC不通知另一個操作正在執行。您需要在您的操作中添加視圖名稱以告訴MVC要呈現哪個視圖:

... 
public ActionResult SimplePost(PostData postData, bool isRichView = true) 
{ 
    ViewBag.IsRichView = isRichView; 
    return View("SimplePost", postData); 
} 
public ActionResult VideoPost(PostData postData, bool isRichView = true) 
{ 
    ViewBag.IsRichView = isRichView; 
    return View("VideoPost", postData); 
} 
...