asp.net mvc - 从javascript链接到.cshtml视图

asp.net mvc - Link to .cshtml view from javascript

本文关键字:链接 cshtml 视图 javascript net mvc asp      更新时间:2023-09-26

如何从javascript文件直接指向.cshtml视图?例如,为什么我不能使用带有 angular.js 的 .cshtml 视图?就像这个例子:

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

当然,有可能有一个返回您想要的任何内容的操作方法,但我很好奇是否可以直接引用剃刀视图。

如注释中所述,您无法直接提供 .cshtml 文件,但是,如果您愿意,则可以使用控制器来呈现内容:

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

然后像引用@Url.Action一样引用它:

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

来自评论

如果你的大部分JavaScript代码在具有Razor访问权限的东西(例如外部.js文件)之外,你仍然可以利用Url构建器,只是必须稍微不同一点。例如,我可能会做这样的事情:

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"); }
@* ... *@

另一种选择是:

1.添加带有编码器模板视图的模板控制器

public class TemplatesController : Controller
{
     public ActionResult EncoderTemplate()
     {
           return View();
     }
}

2.将布局 = null 添加到编码器模板.schtml 视图

@{
    Layout = null;
}
<div>Your html goes here</div>

3.指向编码器模板.schtml,如下所示

.directive('encoder', ($timeout) => {
    return {
        restrict: 'E',
        transclude: true,
        scope: 'isolate',
        locals: { service: 'bind' },
        templateUrl: '/Templates/EncoderTemplate' // you should not add .schtml
    }
});