使用MVC的剃刀模板引擎外(全文MVC剃刀支持) [英] Using the Razor templating engine outside of MVC (with full mvc razor support)

查看:829
本文介绍了使用MVC的剃刀模板引擎外(全文MVC剃刀支持)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找这个圣杯很长一段时间。我通过插件,项目,解决大量的等等。每一个解决方案缺少的东西去了。但是,第一件事情第一。

I was searching for this "holy grail" for a long time. I went through massive amount of plugins, projects, solutions etc. Each solution missing something. But first thing first.

我们要实现的是让posibility渲染视图的字符串(从MVC应用程序所)当然整个proccess应作为类库(不是一个MVC应用程序)

What we want to achieve is to have posibility to render views to string (taken from mvc application) Of course the whole proccess should be done as class library (not an MVC application)

我会想到的是三步procces是这样的:

What i would expect is three step procces like this:


  1. INSTAL从的NuGet一些插件并配置它

  2. 复制粘贴模型和MVC应用程序类库项目视图(重要!查看复制无调整的观点需要任何修改,一些插件)

  3. 写code的一些行说:你好我的'某些插件 - 使我一个名为观点:myExampleView.cshtml'

一个重要条件:我期待的意见完全相同的支持,我会得到的意见MVC(@Html,@RenderBody @RenderSection等)

One important condition : i'm expecting exactly the same support in views as i would get in views in MVC (@Html, @RenderBody @RenderSection etc.)

而作为一个结果,我会得到这个观点redered作为一个字符串 - 就这么简单。是否有可能还是我唯一的梦想?它的插件提供了这一切(甚至更多?:))

And as a result i would get this view redered as a string - simple as that. Is it possible or am i only "dreaming" ? Which plugin offers all of that (and maybe even more ?:) )

现在 - 最接近这个描述是RazorEngine,但我没有看到posibility通过csthml视图名称(这将是足够的传递路径CSHTML视图)当然,我可以写code加载文件内容字符串,并将它传递给RunCompile方法,但是否会有任何RederSection - 它不会得到妥善处理(至少我认为它不会)

For now - closest to this description was RazorEngine but i don't see posibility to pass csthml view name (it would be enough to pass path to cshtml view) Of course i can write code to load file content to string and pass it to RunCompile method but if there would be any "RederSection" - it wouldn't be handled properly (at least i assume it wouldn't)

要总结:我想剃须刀MVC(可用性一样MVC application.In事实上,从MVC应用程序的意见会被简单地复制到该类库),在这个类库我可以引用的一切(包括提到的System.Web)这一点,我会打电话给我的理想的解决方案

To summarize: I want razor MVC (usability the same as in MVC application.In fact, views from MVC application would be simply copied to this class library) In this class library i can reference everything (including mentioned System.Web) This is, what i would call my "ideal solution"

我要的就是调用:

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            string renderedView = MyDreamRazoEngine.Render("MyView", new MyViewModel () { Prop1= "a", Prop2 = "b", Prop3= new List<string>() { "c", "d", "e"})
        }
    }
}

在那里模型(位于/Model/MyViewModel.cs)的定义是:

where model (located in /Model/MyViewModel.cs) definition is :

namespace Example.Models
{
    public class MyViewModel()
    {
        public string Prop1{get;set;}
        public string Prop2{get;set;}
        public List<string> Prop3{get;set;}
    }
}

和视图MyView的(位于/View/MyView.cshtml)的定义是:

and view MyView (located in /View/MyView.cshtml) definition is:

@model Example.Models.MyViewModel
This is my view with Prop1 : @Prop1 and Prop2 : @Prop2 and list :
@foreach (var p in @Model.Prop3)
{
    @{Html.RenderPartial("viewPartial", @p);}
}

和局部视图viewPartial(位于/View/viewPartial.cshtml)的定义是:

and partial view viewPartial (located in /View/viewPartial.cshtml) definition is :

@model String

<span>I present this param3 value @Model</span>

从我可以告诉,一切都(不包括自动文件处理)是可以使用RazorEngine项目来实现。但是,甚至文件处理(完全一样的MVC - 搜索视图和视图的子目录模板)可在此引擎?又或者是我必须用我自己写的?或者一些其他的插件给了我这一切的功能?

From what i can tell, everything (excluding "automatic" files handling) is possible to achieve using RazorEngine project. But maybe even files handling (exactly the same as in MVC - searching for templates in Views and Subdirectories of Views) is available in this engine ? Or is it something i must write by myself ? Or maybe some other plugin gives me all this features ?

@@更新

直接阿尼什我这个解决方案:剃须刀媒体类型格式化了的WebAPI

Anish direct me to this solution : razor media type formatter for webapi

它采用razorengine和支持的意见,以完全相同的方式MVC应用程序(几乎)但是......这是行不通的(肯定我失去了一些东西)什么我现在是:

It uses razorengine and support views, in exactly the same manner as MVC application (almost) But... it doesn't work (for sure i'm missing something) What i have right now is :

public class RazoEngineExample
    {
        private static HttpRequestMessage _request;
        static void Main(string[] args)
        {
            var viewParser = new RazorViewParser(baseTemplateType: typeof(WebApiContrib.Formatting.Razor.HtmlTemplateBase<>));
            var formatter = new RazorViewFormatter(viewParser: viewParser);
            var config = new HttpConfiguration();
            config.Formatters.Add(formatter);

            _request = new HttpRequestMessage();
            _request.SetConfiguration(config);
            _request.RegisterForDispose(config);

            var output = renderView();

            Console.WriteLine(output.Result);

            _request.Dispose();
            _request = null;
        }

        private static async Task<string> renderView()
        {
            var cts = new CancellationTokenSource();
            var view = new ViewResult(_request, "view", new SampleModel() { Prop1 = "p1", Prop2 = "p2", Prop3 = new List<string> { "pe1", "pe2", "pe3" } });

            var response = await view.ExecuteAsync(cts.Token);
            var output = await response.Content.ReadAsStringAsync();
            return output;
        }
    }

据好吧编译它甚至工作(如果我从该视图中删除部分呈现),如果我使用的局部视图我得到这样的错误:

It is compiling allright and it even works (if i remove partial rendering from this view) If i use partial view i get such error:

[ArgumentNullException]值不能为空。参数名:视图

[ArgumentNullException] value cannot be null. parameter name: view

另一件事(但definietly不那么重要)是由razorengine书面控制台消息:

Another thing (but definietly less important) is console message written by razorengine :

RazorEngine:我们可以,如果你使用不清理临时文件RazorEngine上
  默认情况下,ppdomain。创建一个新的AppDomain和使用RazorEngine
  那里。阅读快速启动或
   https://github.com/Antaris/RazorEngine/issues/244 以DET苦恼的!您
  可以忽略这一点,所有后续请清洁...手动消息
  如果よう使用DisableTempFileLocking,这是不推荐使用。
  请清洁
  C:\\用户[USER_ACCOUNT] \\应用程序数据\\本地的\\ Temp \\ RazorEngine_qeouaznq。
  ETT'手动!

RazorEngine: We can't cleanup temp files if you use RazorEngine on the default A ppdomain. Create a new AppDomain and use RazorEngine from there. Read the quickstart or https://github.com/Antaris/RazorEngine/issues/244 for det ails! You can ignore this and all following 'Please clean ... manually' messages if yo u are using DisableTempFileLocking, which is not recommended. Please clean 'C:\Users[user_account]\AppData\Local\Temp\RazorEngine_qeouaznq. ett' manually!

我检查了 - 而且有读/写权限(此文件夹)中设置正确

I've checked - and there are read/write permissions (on this folder) set properly.

请帮助!我是如此接近:)

Please help!!! I'm so close :)

推荐答案

是的,这是所有可能的。类似的问题已经被问previously

Yes this is all possible. Similar questions have been been asked previously

看一看这个回答

之一点上面的答案。

This one points to the answer above.

项目也看起来很有希望,它使用的剃须刀的用的 OWIN

This project also looks promising, it uses Razor with OWIN.

您可能无法使用 @Html @RenderBody @RenderSection Microsoft.AspNet.WebPages <上/ code> 包不依赖的System.Web

You may not be able use @Html, @RenderBody and @RenderSection from the Microsoft.AspNet.WebPages package without a dependency on System.Web.

从我可以告诉,一切都(不包括自动的文件
  处理)是可以使用RazorEngine项目来实现。但也许
  即使文件处理(完全一样的MVC - 搜索
  在视图模板和视图的子目录)在此提供
  引擎?又或者是我必须用我自己写的?或者一些
  其他插件给了我这一切特点?

From what i can tell, everything (excluding "automatic" files handling) is possible to achieve using RazorEngine project. But maybe even files handling (exactly the same as in MVC - searching for templates in Views and Subdirectories of Views) is available in this engine ? Or is it something i must write by myself ? Or maybe some other plugin gives me all this features ?

有是的WebAPI 一个剃须刀媒体类型格式。它暴露了一个 IViewLocator 界面的一部分,它的 API 的和它的默认实现似乎使用你所提到的文件位置约定。您可以在这个项目上展开来实现自己的目标。

There is a razor media type formatter for webapi. It exposes an IViewLocator interface as part of its api and its default implementation appears to use the file location conventions you have mentioned. You may be able to expand on this project to achieve your goals.

这篇关于使用MVC的剃刀模板引擎外(全文MVC剃刀支持)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆