Question

I'm trying to create a partial view in .NET MVC4 that will be a re-usable autocomplete control to use in various places in the application.

I need to use select2 though on client-side for working with a webservice that will serve up the results based on the search terms keyed into the autocomplete.

The problem I'm having is by design Partial Views don't allow scripts section, which I understand. Also, since script bundles are registered after the content body, even if I injected script tag into partial view itself, dependencies would not yet be loaded.

The only thing that comes to my mind is moving my jquery bundle further up before content body is rendered. Then in partial views I could do something like this to init after jquery document.ready is called:

@model MyAutcompleteViewModel
<select id="myautocomplete_@Model.Id"></select>
@* inside of PartialView added this script tag *@
@{
    <script type="text/javascript">
        $(document).ready(function) { 
            // call to init select2 
            $("#myautocomplete_@Model.Id").select2({ 
                // ... config ... 
            });  
        }); 
    </script>
}

Does anyone have a better approach to handling this or even how to accomplish what I'm trying to get at? Thanks for your input.

Was it helpful?

Solution

We were able to resolve this using forloop.htmlhelpers and included using ScriptContext in our partial views so that all JS gets loaded at same time

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