asp.net mvc - 从javascript链接到.cshtml视图
asp.net mvc - Link to .cshtml view from javascript
如何从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
}
});
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 如何使用jQuery自动打开页面上的所有链接
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- jquery动画可以通过编程链接吗
- 在单击href链接的同时下载文件
- 尽管链接成功并已成功下载,但未找到NPM模块
- 制作一个不带HTML a标记但在动画播放完毕后指向其他页面的超链接
- ReactJS映射:如何仅在url变量不为空时呈现html链接
- 单击页面上的链接后高度发生变化
- 将纯文本URL转换为可单击链接
- python-selenium-点击上升链接
- 一点javascript元编程&可链接的设置器
- ng视图外的链接重定向到ng视图内的页面
- 如何调用“;链接_;在onclick事件上使用Javascript
- 链接所有<a>Meteor
- 如何在Angular中的表的所有单元格中添加链接
- 通过链接重定向不;我不在jstree中工作
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- 单击超链接时,如何使用Google Maps API v3缩放地图
- 完全可链接的li元素