Javascript not working in Partial View

岁酱吖の 提交于 2019-12-17 18:52:53

问题


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


回答1:


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.




回答2:


as what I know, partial view need to have the reference of all scripts even though you already reference it in master/layout page. What i always did is create a partial view (_Scripts.cshtml) and put all scripts + stylesheet reference in it. I will then call this partial view at every view:

 @Html.Partial("_Scripts")

Hope this is what you want, thanks :)



来源:https://stackoverflow.com/questions/7941052/javascript-not-working-in-partial-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!