How to specify js and css files to a specific partialview without it interfering with another partialview on the same page?

StackOverflow https://stackoverflow.com/questions/22458087

Question

I have two partial view on the page and each partial has similar information in js and css but I do not want either js or css to interact with eachother. Is this possible in MVC?

Was it helpful?

Solution

I had the same issue. I was using a 3rd party commercial library to pop-up window dialogs, where it was possible I had a reused partial page also containing the same id for a field.

(Imagine they were Customers, and you had a popup for an Order with a CustomerID, and a popup for the customer with a CustomerID.)

I really had to learn how the commercial library I was using worked, but I was able to tell that with certain options it used an iframe (instead of just moving around a div). But when setting the options such that it was using the iframe, of course my problem went away - because these really are separate pages and the javascript will only bridge the gap if you try.

So ultimately, using frames is generally my last resort, but there is no simpler way to have two partial views displayed yet lightly sandboxed from causing id errors in each other.


To avoid using an iframe, you could still have 2 forms posting the same field name, yet avoid the JavaScript errors if they had different ids. You could further make small changes to keep the css selectors from matching both forms.

The below is only pseudo code to explain the idea:

<script type="text/css">

  form.customer > input { border: 1px solid red; }

  form.order > input { border: 3px dotted blue; }

</script>

<script type="text/JavaScript">
function doSomething()
{
    CustomerId_Customer.text = "1";
}
</script>

<form class="customer" action="/Customer/Save">
<input type="text" name="CustomerId" id="CustomerId_Customer" />
</form>    

<script type="text/JavaScript">

function doSomethingElse()
{
    CustomerId_Order.text = "3";
}

</script>       

<form class="order" action="/Order/Save">
<input type="text" name="CustomerId" id="CustomerId_Order" />
</form>

<a href="javascript:doSomething();"> Do Something</a>    
<a href="javascript:doSomethingElse();"> Do Something Else</a>

Notice this requires various changes to your original partial views. Again, if you want a magic tag to wrap around them that fixes all the problems... then we're talking iframes.

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