简体   繁体   English

仅在特定视图的HTML标记中添加属性?

[英]adding attributes in HTML tag of specific views only?

I am working on a MVC application with razor view engine. 我正在使用剃刀视图引擎开发MVC应用程序。

HTML, Head and Body tags are placed in shared view _Layout.cshtml and other views are using this as layout. HTML,Head和Body标签放在共享视图_Layout.cshtml中,其他视图使用它作为布局。

While supporting application I am in need to add a custom attribute in some of pages (not in all pages). 在支持应用程序的同时,我需要在某些页面中添加自定义属性(不是在所有页面中)。 If I add attribute in layout it will appear in all pages. 如果我在布局中添加属性,它将出现在所有页面中。 Can you pleased guide me how adding an attribute can be managed only in desired pages. 您能否高兴地指导我如何仅在所需页面中管理添加属性。

Below is my html tag with attribute: 下面是我的带有属性的html标签:

<html ng-app="business_rules">

You can create a Layout where you need all these attributes and just refer this layout for desired pages using 您可以创建一个需要所有这些属性的布局,并使用该布局引用所需的页面

@{
   Layout = "Path/To/Layout.cshtml";
}

on the top of those pages. 在这些页面的顶部。

For rest of the pages, you will use the different layout without those attributes. 对于其余页面,您将使用不具有这些属性的不同布局。

You can define the Layout form the controller too. 您也可以从控制器中定义布局。 It can be done as below: 它可以如下完成:

public ActionResult Index()
{
    MyMOdel model = new MyMOdel ();
    //TO DO:
    return View("Index", "_AdminLayout", model);
}

I would use jquery. 我会用jquery。 Just add on pages where you need this attribute following code: 只需在以下代码中添加您需要此属性的页面:

<script>
$(document).ready(function(){
$('html').attr("ng-app", "business_rules")
});
</script>

I came across the exact same problem right now and the best solution I came up with was this below (I don't really want to add an entirely separate layout just for an attribute on the body tag). 我现在遇到了完全相同的问题,我想出的最佳解决方案如下(我真的不想为body标签上的属性添加完全独立的布局)。 You've got a couple of suggestions on the asp net forums as well 你在asp网络论坛上也有一些建议

I added an item to the view bag, a (probably overly) generic one called BodyAttributes: 我在视图包中添加了一个项目,一个名为BodyAttributes的(可能是过度的)通用名称:

ViewBag.BodyAttributes = "ng-app=\"moduleName\"";

Then I render this in pure htlm on the body tag 然后我在body标签上用纯htlm渲染它

<body @Html.Raw(ViewBag.BodyAttributes)>

This keeps your layout non page specific and the angular doesn't need to be bootstrapped on every view. 这样可以保持布局非页面特定,并且不需要在每个视图上引导角度。 Plus, whether or not the angular is bootstrapped is now controlled from within the view itself where it belongs. 此外,角度是否自动引导现在可以从它所属的视图本身内进行控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM