15

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

Community
  • 1
  • 1
Suresh Ganapathy
  • 187
  • 1
  • 2
  • 11

2 Answers2

31

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.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

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")
Necoras
  • 6,743
  • 3
  • 24
  • 45
shennyL
  • 2,764
  • 11
  • 41
  • 65
  • I tried Html.RenderPartial ; Same issue There is no multiple inclusion of files... I am alreday the same thing as told by user834754.. Still I have issue!!! – Suresh Ganapathy Oct 30 '11 at 08:03