Html.操作错误行为
本文关键字:错误 操作 Html | 更新日期: 2023-09-27 18:23:37
我有这个控制器:
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
}
所以在那之后,我得到了错误:找不到视图"Post"或示例,或者没有不支持搜索的处理程序视图。在以下位置搜索:
~/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"视图?
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);
}
...