ASP.NET MVC 在控制器中获取某个视图动态的HTML代码
如果我们需要动态的用AJAX从服务器端获取HTML代码,拼接字符串是一种不好的方式,所以我们将HTML代码写在cshtml文件中,然后通过代码传入model,动态获取cshtml中的HTML代码
当然,我们想要使用通用的方法去获取cshtml,就必须重写RazorViewEngine视图引擎,配置视图搜索位置
在查找一个视图时,Razor视图引擎遵循了MVC框架早期版本建立起来的约定。例如,如果你请求与Home控制器相关的Index视图,Razor会审查这样的视图列表:
● ~/Views/Home/Index.cshtml
● ~/Views/Home/Index.vbhtml
● ~/Views/Shared/Index.cshtml
● ~/Views/Shared/Index.vbhtml
正如你现在知道的,Razor实际上不会在磁盘上查找这些视图文件,因为它们还没有被编译成C#类。Razor查找的是表示这些视图的编译类。.cshtml文件是含有C#语句的模板(我们正在使用的这种),而.vbhtml文件含有Visual Basic语句。
你可以通过生成一个RazorViewEngine子类,来改变Razor搜索的这种视图文件。这个类是Razor的IViewEngine实现。它建立于一组基类之上,这些类定义一组用来确定搜索哪种视图文件的属性。这些属性如表所描述。
Property 属性 | Description 描述 | Default Value 默认值 |
ViewLocationFormats MasterLocationFormats PartialViewLocationFormats | The locations to look for views, partial views, and layouts 查找视图、分部视图、以及布局的位置 | "~/Views/{1}/{0}.cshtml", "~/Views/{1}/{0}.vbhtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared/{0}.vbhtml" |
AreaViewLocationFormats AreaMasterLocationFormats AreaPartialViewLocationFormats | The locations to look for views, partial views, and layouts for an area 查找一个区域的视图、分部视图、及布局的位置 | "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/{1}/{0}.vbhtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.vbhtml" |
这些属性先于Razor的引入,这是每组三个属性具有相同值的原因。每个属性是一个字符串数组,它们是用复合字符串格式化符号来表示的。以下是与占位符对应的参数值:
● {0} represents the name of the view. {0} 表示视图名
● {1} represents the name of the controller. {1} 表示控制器名
● {2} represents the name of the area. {2} 表示区域名 为了修改搜索位置,你要生成一个派生于RazorViewEngine的新类,并修改表所描述的一个或多个属性值。
在Infrastructure文件夹中新建一个CustomRazorViewEngine类
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication1.Infrastructure { public class CustomRazorViewEngine : RazorViewEngine { public CustomRazorViewEngine() { ViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared_PartialView/{0}.cshtml"//指定查找某个文件的路径 }; PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml", "~/Views/Shared_PartialView/{0}.cshtml"////指定查找某个文件的路径 }; } } }
我们在Global.asax的Application_Start方法中,用ViewEngines.Engines集合来注册我们的这个派生视图引擎,像这样:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new CustomRazorViewEngine()); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
获取html字符串的方法以及如何调用
public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { string html = this.ControllerContext.RenderViewToString("_CommonPartial", new UserViewModel() { UserName="haha"}); return View(new UserViewModel() { IsEnable = false, UserCode = "aa" }); } } public static class HelperExtensions { public static string RenderViewToString(this ControllerContext context, string viewName, object model) { if (string.IsNullOrEmpty(viewName)) viewName = context.RouteData.GetRequiredString("action"); context.Controller.ViewData.Model = model; using (var sw = new StringWriter()) { ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName); var viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw); try { viewResult.View.Render(viewContext, sw); } catch (Exception ex) { throw; } return sw.GetStringBuilder().ToString(); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2008-03-18 ASP.NET 2.0(C#)系列文章索引
2008-03-18 ASP.NET AJAX系列文章索引
2008-03-18 [翻译]ASP.NET 3.5中的ListView控件和DataPager控件
2008-03-18 .net3.5超酷体验