Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript not working in Partial View

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...

like image 534
Suresh Ganapathy Avatar asked Oct 29 '11 19:10

Suresh Ganapathy


People also ask

Can partial view have controller?

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.

How do I pass a model into partial view?

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.

Can partial view have JavaScript?

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.

Can we use jQuery in partial view?

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.


2 Answers

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.

like image 101
Darin Dimitrov Avatar answered Oct 17 '22 23:10

Darin Dimitrov


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")
like image 22
shennyL Avatar answered Oct 18 '22 01:10

shennyL