Question

I am working on a MVC application with razor view engine.

HTML, Head and Body tags are placed in shared view _Layout.cshtml and other views are using this as layout.

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 ng-app="business_rules">
Was it helpful?

Solution

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

OTHER TIPS

I would use 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). You've got a couple of suggestions on the asp net forums as well

I added an item to the view bag, a (probably overly) generic one called BodyAttributes:

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

Then I render this in pure htlm on the body tag

<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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top