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

问题描述

如何从 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?
        }
    });

当然可以有一个 action 方法返回你想要的任何东西,但我很好奇是否可以直接引用 razor 视图.

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 一样引用它:

Then reference it like you would with @Url.Action:

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

来自评论

如果您在具有 Razor 访问权限的内容(例如外部 .js 文件)之外拥有大部分 JavaScript 代码,您仍然可以利用 Url 构建器,只需稍微改变一下即可.例如,我可能会执行以下操作:

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

~/Views/Template/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"); }
@* ... *@

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

11-01 04:00