I have an html helper in MVC3 that renders a custom section of html that is being used as a search control. The issue is that there is javascript (jquery) that has been written to interact with the control (it really should be used JUST for this control). Is there a way to make the javascript embedded so that the control continues to have the javascript functionality. (With creating the helper, we can control how the html is structured and make it easier to write the javascript. This would standardize the use of the control across out app).
ex.
<div>
@Html.SearchControl("searchControlSelector")
</div>
<script>
$("searchControlSelector").timeout();
<script>
I want to be able to set the ‘timeout’ functionality when calling the @Html.SearchControl([some params]) so that the javascript and helper are combined and users of the helper do not have to worry about what selectors they should use when calling ‘timeout’. Does anyone know how to achieve this? Is there a better way of handling this?
It is hard to make completely reusable html helper with single shared javascript file.
At first it is not possible to output only one
<script>$(".searchControl").timeout()</script>code block per page without using additional method calls in layout page etc.You could add your own control-specific data-attribute like data-search-control and use it in selectors like
$("input[data-search-control]").timeout()to distinct only HTML produced by your helper.If it is ok for you to have multiple scripts block on page don’t forget they will be executed few times so you need to care about preventing multiple execution. You may associate some data with HTML nodes already processed by the script using for example jQuery
$("").data()method. Or as option you may check if specified object in global scope is declared and if it is then do nothing otherwise declare it and call your method.