我重新修改了View的映射规则,代码如下
public override void OnResultExecuting(ResultExecutingContext filterContext) { var currentUserTemplate = this.GetCurrentUserTemplate(); var template = string.IsNullOrEmpty(currentUserTemplate) ? this.DefaultTemplateName : currentUserTemplate; var controller = filterContext.RequestContext.RouteData.Values["Controller"].ToString(); var action = filterContext.RequestContext.RouteData.Values["Action"].ToString(); if (filterContext.Result is ViewResult) { var viewResult = filterContext.Result as ViewResult; if (viewResult != null) { if (string.IsNullOrWhiteSpace(viewResult.ViewName)) { viewResult.ViewName = string.Format("~/Views/{0}/{1}/{2}.{3}", controller, template, action, this.TemplateFileExtension); return; } } } base.OnResultExecuting(filterContext); }
这样如果不用Partial,能按照我的意愿对应到我要的View,例如输入http://localhost:2539/user/index ,对应到~/Views/User/pc/Index.cshtml,然后Index.cshtml又加载片段的代码@Html.Partial("_Sidebar"),_Sidebar.cshtml放置于~/Views/User/pc/Shared/_Sidebar.cshtml
运行后报错
未找到分部视图“_Sidebar”或没有视图引擎支持搜索的位置。搜索了以下位置:
~/Views/user/_Sidebar.aspx
~/Views/user/_Sidebar.ascx
~/Views/Shared/_Sidebar.aspx
~/Views/Shared/_Sidebar.ascx
~/Views/user/_Sidebar.cshtml
~/Views/user/_Sidebar.vbhtml
~/Views/Shared/_Sidebar.cshtml
~/Views/Shared/_Sidebar.vbhtml
不是ViewResult?
PartialView是不是有別的規則?
~/Views/User/pc/Index.cshtml 这个是View的路径
~/Views/User/pc/Shared/_Sidebar.cshtml 这个是片段的路径,在Index.cshtml 用Html.Partial("_Sidebar") 就提示上面的错误,我是在filter机制里修改了Index.cshtml的ViewName,可是Html.Partial搜索文件的时候是去~/Views/user/_Sidebar.cshtml 和~/Views/Shared/_Sidebar.cshtml搜索的,不会去~/Views/User/pc/下搜索
@ludi:
我的意思是
你在filter判斷ViewResult改變規則
PartialView會不會不在ViewResult下
而在其它類下
@RosonJ: 在filterContext.Result获取到的View只能获取到Index.cshtml,而_Sidebar.cshtml不会获取,应该是在运行到Html.Partial语句的时候才回去查找这个片段,但是Html.Partial不知道我已经对路径做过处理了,还去默认的~/Views/user/_Sidebar.cshtml 和~/Views/Shared/_Sidebar.cshtml下搜索
@ludi:
if (filterContext.Result is PartialViewResult) { var viewResult = filterContext.Result as PartialViewResult; if (viewResult != null) { if (string.IsNullOrWhiteSpace(viewResult.ViewName)) { viewResult.ViewName = string.Format("~/Views/{0}/{1}/{2}.{3}", controller, template, action, this.TemplateFileExtension); return; } } }
你需要這一段,action return View跟PartialView不一樣
你需要增加判斷..