从javascript链接到.cshtml视图

iLe*_*ing 7 javascript asp.net-mvc angularjs angularjs-directive

你如何从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?
        }
    });
Run Code Online (Sandbox Code Playgroud)

当然可以有一个返回你想要的动作方法,但我很好奇是否可以直接引用剃刀视图.

Bra*_*tie 10

如评论中所述,您无法直接提供.cshtml文件,但是,如果您选择,则可以使用控制器呈现内容:

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

然后像你一样参考它@Url.Action:

{
    ....
    templateUrl: '@Url.Action("Encoder", "Template")'
}
Run Code Online (Sandbox Code Playgroud)

来自评论

如果您拥有Razor访问权限之外的大多数JavaScript代码(例如外部.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();
    }
}
Run Code Online (Sandbox Code Playgroud)

〜/查看/模板/ 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")
Run Code Online (Sandbox Code Playgroud)

Index.cshtml(或任何视图)

@* ... *@
@{ Html.RenderAction("Index", "Template"); }
@* ... *@
Run Code Online (Sandbox Code Playgroud)


小智 6

另一种选择是:

1.使用EncoderTemplate视图添加TemplatesController

public class TemplatesController : Controller
{

     public ActionResult EncoderTemplate()
     {

           return View();
     }

}
Run Code Online (Sandbox Code Playgroud)

2.将Layout = null添加到EncoderTemplate.schtml视图

@{
    Layout = null;
}

<div>Your html goes here</div>
Run Code Online (Sandbox Code Playgroud)

3.指向EncoderTemplate.schtml,如下所示

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