Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call JavaScript from within an ASP.NET MVC Partial View

I have created an ASP.NET MVC partial view and I am calling it via the HTML.Action helper method:

@Html.Action("GetMyPartialView", "MyController", new { myParameter})

The partial view contains a control that needs some JavaScript to be called (a JavaScript library in an external JavaScript file). How can I call this JavaScript code from within my partial view.

I tried using the script element inside the partial view:

<script>
    MyJavaScriptFunction();
</script>

This did not work. Probably the external JavaScript files (e.g. jQuery) have not been loaded at that time.

What is the recommended way to execute JavaScript code when a partial view has been rendered?

like image 727
Alexander Avatar asked May 27 '15 09:05

Alexander


People also ask

Can we call partial view inside partial view in MVC?

To call a partial view from another partial view, we follow the same approach as we follow when we call partial view from the content page. Let's take an example. This is the code of 1st partial view. Notice that in above partial view, we are calling another partial view named "_View2" that is created below.

How can we call a partial view in view of ASP NET core?

In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.

Can we use jquery in partial view?

Then, in the view page, after the document is ready, you can use JQuery to get the Selected value, if the selected value is not the first option ("0"), load the partial view to display the related content. If the answer is the right solution, please click "Accept Answer" and kindly upvote it.


1 Answers

You cannot use java script sections in partial views. They simply don't work. So keep the @section JavaScript in the main view in order to register scripts and then render the partial view

like image 111
Sachu Avatar answered Sep 20 '22 16:09

Sachu