我一直在尝试 ASP.NET MVC 并且有一个问题,或者可能是我做错了什么。只是在开发一个普通的网站来拓宽自己的技能。抱歉这个问题并不简短。
好的,这是场景:当用户访问home/index时,页面应该显示产品列表和文章列表。文件布局如下(DAL 是我的数据访问层):
Controllers Home IndexTranslated version:
Views Home Index 继承自 ViewPage Product List 继承自 ViewUserControl<IEnumerable<DAL.Product>> Single 继承自 ViewUserControl<DAL.Product> Article List 继承自 ViewUserControl<IEnumerable<DAL.Article>> Single 继承自 ViewUserControl<DAL.Article>
我在尝试使用ASP.NET MVC,有一个问题,或者可能是我做错了什么。我正在制作一个简单的网站以提高自己的技能水平。很抱歉这个问题并不简洁明了。
下面是场景:当用户访问home/index时,页面应该显示产品列表和文章列表。文件布局如下(DAL代表数据访问层):
控制器 Home Index
视图 Home Index 继承自ViewPage Product List 继承自ViewUserControl<IEnumerable<DAL.Product>> Single 继承自ViewUserControl<DAL.Product> Article List 继承自ViewUserControl<IEnumerable<DAL.Article>> Single 继承自ViewUserControl<DAL.Article>
Controllers.HomeController.Index produces a View whose ViewData contains two entries, a IEnumerable<DAL.Product> and a IEnumerable<DAL.Article>.
View.Home.Index will use those view entries to call:
Html.RenderPartial("~/Views/Product/List.ascx", ViewData["ProductList"])
and Html.RenderPartial("~/Views/Article/List.ascx", ViewData["ArticleList"])
View.Product.List will call
foreach(Product product in View.Model)
Html.RenderPartial("Single", product);
View.Article.List does something similar to View.Product.List
然而,这种方法是失败的。虽然这个方法在我看来是有意义的,但或许有更多经验的MVC平台用户能够识别出更好的方法。
上述代码在View.Product.List内部产生了一个错误。调用Html.RenderPartial("Single",...)
时会提示"Single"视图未被找到。该错误信息如下:
The partial view 'Single' could not be found. The following locations were searched: ~/Views/Home/Single.aspx ~/Views/Home/Single.ascx ~/Views/Shared/Single.aspx ~/Views/Shared/Single.ascx
由于我是从Product视图中调用RenderAction(),我期望运行时会在Views\Product中寻找"Single"视图。然而,事实上查找的相对位置是与调用原始视图的控制器(/Controller/Home 调用 /Views/Product)相关的,而不是当前视图。
所以,我可以通过更改Views\Product来修复这个问题,使其如下:
View.Product.List will call
foreach(Product product in View.Model)
Html.RenderPartial(<b>"~/Views/Product/Single.ascx"</b>, product);
取代
View.Product.List will call
foreach(Product product in View.Model)
Html.RenderPartial(<b>"Single"</b>, product);
这个修复方法可行,但是我不明白为什么需要指定完整的视图路径。按照我的理解,相对名称应该相对于当前视图的路径进行解释,而不是原始控制器的视图路径。除了在典型情况下它们相同的情况下之外,我无法想象出任何有用的情况,在这种情况下,将名称解释为相对于控制器视图而不是当前视图是有用的。
这个时候我应该加上一个问号?以强调这实际上是一个问题。