在服务器和客户端之间共享mustache / nustache模板。 ASP.NET MVC

时间:2012-03-14 12:38:16

标签: ajax asp.net-mvc templates razor mustache

我在客户端使用 mustache.js ,在ASP.NET MVC3项目中使用 Nustache

我在服务器上的View文件夹中有Person.mustache模板,我这样使用:

@Html.Partial("Person")

来自Razor主视图(Index.cshtml)。

但是如何将其转移到客户端?浏览器无权访问Views文件夹以获取模板的原始内容。不知何故,我必须有一种方法来包含在服务器上输出Person.mustache模板的HTML原始文本。如果我从Razor视图中需要它,它会编译它,因为它是普通的服务器模板引擎。

请有人能提出任何想法吗?感谢。

3 个答案:

答案 0 :(得分:3)

嗯,我做了一些有用的东西,也许有人会提出更好的解决方案。这是:

@Html帮助者的扩展:

public static class ViewExtensions
{
    public static IHtmlString RenderRawContent(this HtmlHelper helper, string serverPath)
    {
        string filePath = HttpContext.Current.Server.MapPath(serverPath);

        //load from file
        StreamReader streamReader = File.OpenText(filePath);
        string markup = streamReader.ReadToEnd();
        streamReader.Close();

        return new HtmlString(markup);

    }
}

在Razor索引页面的主视图中

@using MyProject.Helpers;

<script type="text/template" id="person_template">

    @Html.RenderRawContent("~/Templates/Person.mustache")

</script>

答案 1 :(得分:1)

您可能希望公开一个可以返回部分视图内容的新控制器。 E.g:

public class TemplateController : Controller
{
  public PartialViewResult Get(string name)
  {
    return PartialView(name);
  }
}

用它和路线:

routes.MapRoute("Templates", "templates/{name}",
  new { controller = "Template", action = "Get" });

然后我可以从客户端调用(在本例中我使用的是jQuery):

var model = { name: "Matt" };
$.ajax({
  url: "/templates/person",
  success: function(r) {
    var html = Mustache.render(r, model);
    $("body").append(html);
  }
});

答案 2 :(得分:0)

将文件命名为Person.mustache.cshtml,并在Index.cshtml

<script type="text/template" id="person_template">
    @Html.Partial("Person.mustache")
<script type="text/template" id="person_template">

当框架为您执行此操作时,无需编写帮助程序来提供文件。

相关问题