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();
            }
        }
    }

 

posted @ 2014-03-18 11:42  学亮  阅读(5994)  评论(7编辑  收藏  举报