我知道我的问题是什么,但不知道如何修复它所以我希望这里的天才可以提供帮助。我有一个控制器,我想从网址中获取一条信息,然后重定向到该网站。我的控制器做了它的事情并返回视图,但视图中有一部分并且视图引擎找不到它?
所以这是设置。
控制器映射路由为:
//marketing/tracking
routes.MapRoute("CampaignTracking",
"{save}/{campaignid}",
new { controller = "CampaignTracking", action = "Index" });
这很有效。接下来是我的控制器:
public ActionResult Index(Int32 campaignID)
{
var model = new ...snip...
return View("../Customer/Login", model);
}
现在我最初得到的错误无法找到视图,因为它正在查看CampaignTracking文件夹,我有:
return View("Customer/Login", model);
所以我改变了它,如上所示用../来到正确的位置。现在它找到了Login.cshtml,但是在login.cshtml中它呈现了局部,并且它再次寻找在Campaigntracking中找到部分内容。
我可以废除CampaignTracking控制器并将操作结果移动到CustomerController中,但更愿意将其保留在自己的控制器中,因为这可能会增长并且不会真正归入客户。
根据nicu Janga
我改变了控制器:
return View(@"~/Views/Customer/Login.cshtml", model);
和我的login.cshtml中的部分内容:
@Html.Partial(@"~/Views/Customer/...etc.cshtml")
但我想知道为什么。我可以理解视图引擎如何从控制器中混淆但是一旦使用return View(@“〜/ Views / Customer / Login.cshtml”,模型)进行了修正;不应该将正确的路径传播到login.cshtml ???
显然不是,但我不理解?
答案 0 :(得分:2)
你可以尝试这个:
return View(@"~/Views/Customer/Login.cshtml",model);
它有效吗?
答案 1 :(得分:2)
让我看看我是否可以为您填写一些细节。首先,假设我们刚刚将以下控制器添加到空项目中:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
现在,让我们假设我们没有费心添加Index.cshtml
视图,所以当我们运行它时,它会告诉我们视图丢失了。看一下该例外所附的消息:
The view 'Index' or its master was not found or no view engine supports
the searched locations. The following locations were searched:
~/Views/home/Index.aspx
~/Views/home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/home/Index.cshtml
~/Views/home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
这些是MVC尝试查找视图时搜索的确切位置。在大多数情况下,如果您使用C#和MVC,那么您需要关注的只有两个:
~/Views/home/Index.cshtml
~/Views/Shared/Index.cshtml
这意味着如果在指定视图名称时未提供路径,则始终会检查这两个位置。因此,如果我们从HomeController
:
return View("Test");
MVC将在~/Views/Home/Test.cshtml
然后~/Views/Shared/Test.cshtml
查找此视图。关于这一点的好处是它的一致。它总是以同样的方式查找视图。
现在,让我们使用一个更复杂的例子(再次假设我们在HomeController
):
return View("../SomeDirectory/Test.cshtml");
这将通过以下方式进行寻找:
~/Views/Home/../SomeDirectory/Index.cshtml
~/Views/Shared/../SomeDirectory/Index.cshtml
首先看一下~/Views/Home/../SomeDirectory/Index.cshtml
,这实际上意味着它在这里搜索视图:~/Views/SomeDirectory/Index.cshtml
。显然,这不是您的观点所在,同样适用于~/Views/Shared/../SomeDirectory/Index.cshtml
最终的位置。
这里要记住的重要事项是~
表示您网站的相对根。它将始终从您网站的根目录开始工作,这意味着您始终可以确切地知道发生了什么。通过这样做
return View("~/Views/Home/Index.cshtml");
你告诉MVC 确切地在哪里找到你的观点,而不是让MVC的惯例规则为你决定。这意味着无论何时为MVC指定位置以查找视图,它都将仅搜索该位置。因此,return View("~/Views/Home/Index.cshtml")
仅会在~/Views/Home/Index.cshtml
搜索该视图。如果它找不到那里的视图,你将得到与以前相同的异常,但它会给你一个略有不同的消息:
The view '~/Views/Home/Index.cshtml' or its master was not found or no view
engine supports the searched locations. The following locations were searched:
~/Views/Home/Index.cshtml
注意它没有在其他位置搜索视图。