我需要从一个约会驱动的位置写一个js文件的内容(如〜/ ClientApp / Controllers / Home / Home.js,如果加载位于〜/ Views / Home / Home.cshtml的视图).我该如何做?
示例:如果文件〜/ Views / Home / Home.cshtml如下所示:
<div id="some-partial-view"> <!-- ... --> </div>
而文件〜/ ClientApp / Controllers / Home / Home.Controller.js看起来像
function HomeController() { //some code }
然后Web服务器返回的渲染视图应该是(如果使用fiddler)
<!--ommitted <html> <body> tags --> <div id="some-partial-view"> <!-- ... --> </div> <script type="text/javascript"> function HomeController() { //some code } </script>
<div id="some-partial-view" ng:Controller="HomeController"> <!-- ... --> </div> @Html.IncludeController("HomeController")
但是,我不想在所有部分视图中重复.
有任何想法吗?
解决方法
你可以编写自定义视图:
public class MyRazorView : RazorView { public MyRazorView(ControllerContext controllerContext,string viewPath,string layoutPath,bool runViewStartPages,IEnumerable<string> viewStartFileExtensions,IViewPageActivator viewPageActivator) : base(controllerContext,viewPath,layoutPath,runViewStartPages,viewStartFileExtensions,viewPageActivator) { } protected override void RenderView(ViewContext viewContext,TextWriter writer,object instance) { base.RenderView(viewContext,writer,instance); var view = (BuildManagerCompiledView)viewContext.View; var context = viewContext.HttpContext; var path = context.Server.MapPath(view.ViewPath); var viewName = Path.GetFileNameWithoutExtension(path); var controller = viewContext.RouteData.GetrequiredString("controller"); var js = context.Server.MapPath( string.Format( "~/ClientApp/Controllers/{0}/{0}.{1}.js",viewName,controller ) ); if (File.Exists(js)) { writer.WriteLine( string.Format( "<script type=\"text/javascript\">{0}</script>",File.ReadAllText(js) ) ); } } }
以及一个自定义视图引擎,当要求部分视图时,它将返回此自定义视图:
public class MyRazorViewEngine : RazorViewEngine { protected override IView CreatePartialView(ControllerContext controllerContext,string partialPath) { return new MyRazorView( controllerContext,partialPath,null,false,base.FileExtensions,base.ViewPageActivator ); } }
这将在Application_Start中注册:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new MyRazorViewEngine()); }
您可能需要调整一些路径,因为在您的问题中,js所在的位置不太清楚,但通常您应该在答案中有足够的详细信息.