7

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

もちろん、何でも好きなものを返すアクション メソッドを持つことは可能ですが、カミソリ ビューを直接参照できるかどうかに興味があります。

4

2 に答える 2

10

コメントで述べたように、.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"); }
@* ... *@
于 2013-01-31T17:44:05.470 に答える