This problem is similar to what is described in Execute Javascript inside a partial view in ASP.NET MVC
The below piece of code in index.cshtml is working fine...
<label for="locationOfSearch"> in :</label> @Html.TextBox("locationOfSearch")
<input type="submit" value="Search" style="background-color:Green"/>
@section JavaScript {
<script type="text/javascript">
$(document).ready(function () {
$("#locationOfSearch").autocomplete({
source: '@Url.Action("AutocompleteAsyncLocations")'
})
});
</script>
}
But when I copy and paste the above code and the respective script files to a another view and then in index.cshtml if I call Html.Partial(new view name), Autocomplete is not working...
Kindly let me know how I solve it without much modification...
It does not require to have a controller action method to call it. Partial view data is dependent of parent model. Caching is not possible as it is tightly bound with parent view (controller action method) and parent's model.
To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.
JavaScript functions can be bound to elements on the partial view; the partial view is rendered at the same time as the parent view. This happens when loading the partial view with a @Html.
Partial helper functions will not work with jQuery Client Side scripting. The Partial View will be populated and fetched using jQuery AJAX and finally it will be rendered as HTML inside DIV using jQuery.
You cannot use sections in partial views. They simply don't work. So you will have to keep the @section JavaScript
in the view in order to register scripts and then render the partial which will contain only the markup. You could also write custom helper methods to achieve this as shown in this answer.
Partial views need to have a reference to all scripts, even though you've already referenced it in the master/layout page. Create a partial view (ex: _Scripts.cshtml) and put all of your scripts and stylesheet references in it. Then call this partial view in every view:
@Html.Partial("_Scripts")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With