I'm using MVC 5 and I have a partial view which renders a styled select:
@model Int16
<div class="select">
<span class="arr"></span>
<select>
<option>2016</option>
</select>
</div>
Notice the model. I'm passing in an int that will change the width of the select. This is how I render the partial view in Index.cshtml and other views:
@Html.Partial("~/Views/Components/_select.cshtml",(short) 300)
So in this example, I want the select to have a width of 300px. I added the following javascript in my partial view, so now it looks like this:
@model Int16
<script>
$(function () {
debugger;
var width = '@Model';
if (width !== '') {
$('div.select select').css(width, width + 'px');
}
});
</script>
}
<div class="select">
<span class="arr"></span>
<select>
<option>2016</option>
</select>
</div>
Two problems:
- The code isn't working. The javascript isn't being called, so the width of the select is not changing. The debugger statement is not being hit.
- I don't like the javascript being inside the partial view. I will have a page with 8 of these selects (hence the reason for the reusable html) but with the javascript being in the partial view, that code will be on the page 8 times. Very inefficient.
First and foremost, how do I get the javascript to fire in a partial view? (I would like this answered because I cant see for the life of me why it isn't firing).
Next,what would be a better place to put the javascript so the width of the selects inside the partial view will be changed?
Thanks