链接到.cshtml从JavaScript视图 [英] Link to .cshtml view from javascript

查看:192
本文介绍了链接到.cshtml从JavaScript视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么能直接指向从JavaScript文件中的.cshtml看法?
例如,为什么不能我用一个angular.js看法.cshtml?
像在本实施例

How can you point directly to a .cshtml view from javascript file? For example why can't I use a .cshtml view with angular.js? like in this example:

 .directive('encoder', ($timeout) => {
        return {
            restrict: 'E',
            transclude: true,
            scope: 'isolate',
            locals: { service: 'bind' },
            templateUrl: 'encoderTemplate.cshtml' // <-- that's not possible?
        }
    });

这当然可能有一个返回任何你想要的操作方法,但我很好奇,如果有可能直接引用到剃刀视图。

It's of course possible to have an action method that returns whatever you want, but I'm curious if it's possible to reference directly to the razor view.

推荐答案

由于在评论中提到的,你不能直接起到了.cshtml文件,但是,你可以使用一个控制器来呈现内容,如果你选择:

As mentioned in a comment, you can't serve up .cshtml files directly, However, you can use a controller to render the content if you so choose:

public class TemplateController : Controller
{
    // create a ~/Views/Template/Encoder.cshtml file
    public PartialViewResult Encoder()
    {
        return PartialView();
    }
}

然后用 @ Url.Action 引用它,就像您:

{
    ....
    templateUrl: '@Url.Action("Encoder", "Template")'
}


从注释

如果你有大部分的JavaScript code的东西,有剃刀接入(例如外部.js文件),你仍然可以利用网址构建器之外,就必须这样做有点不同。举例来说,我可能会做这样的事情:

If you have most of the JavaScript code outside of something that has Razor access (e.g. external .js file) you can still take advantage of the Url builder, just have to do so a little differently. For instance, I may do something like:

public class TemplateController : Controller
{
    // Add a child method to the templates controller that outputs default
    // configuration settings (and, since it's a child action, we can re-use it)
    [ChildActionOnly]
    public PartialViewResult Index()
    {
        // You could build a dynamic IEnumerable<ConfigRef> model
        // here and pass it off, but I'm just going to stick with a static view
        return PartialView();
    }
}

〜/查看/模板/ Index.cshtml

<script type="text/javascript">
  if (typeof window.App === 'undefined'){
    window.App = {};
  }
  App.Templates = {
    Encoder: '@Url.Action("Encoder", "Template")',
    Template1: '@Url.Action("Template1", "Template")',
    Template2: '@Url.Action("Template2", "Template")'
  };
</script>
@*
   the template files would then reference `App.Templates.Encoder`
   when they need access to that template.
*@
@Scripts.Render("~/js/templating")

Index.cshtml (或者其他任何视图)

@* ... *@
@{ Html.RenderAction("Index", "Template"); }
@* ... *@

这篇关于链接到.cshtml从JavaScript视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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