Alexander
Alexander

Reputation: 1061

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?

Upvotes: 7

Views: 20708

Answers (4)

Jim Berg
Jim Berg

Reputation: 659

I just ran into this problem. You can call a javascript function in the partial view from within the partial view. I created a hidden field and defined the onclick event to call the function I needed to call to initialize the dialog in the partial view. Then I triggered the click event for that hidden field.

Code in partial view:

 <input type="hidden" id="initializeDialog" onclick="initializeDialog();" />

<script>
    function initializeDialog(){
        // Do stuff
    }
</script>

Code in containing view:

<script>
    $('#InitializeDialog').trigger('click');
</script>

Upvotes: 0

Gera
Gera

Reputation: 149

You can use ajax call to achieve this.

$(document).ready(

    //Do ajax call  
        $.ajax({
        type: 'GET',
        url: "controller action url",    
        data : {                          
                  //Data need to pass as parameter                       
               },           
        dataType: 'html', //dataType - html
        success:function(result)
        {
           //Create a Div around the Partial View and fill the result
           $('#partialViewContainerDiv').html(result);                 
        }

//Action

       public ActionResult GetMyPartialView(int myParameter)    
       {    
         //return partial view instead of View   
          return PartialView("YourView", resultSet);   
        }

Upvotes: 1

Spider man
Spider man

Reputation: 3330

I had almost similar situation. What i did was added javascript in the main view. You try add javascript in the main view from where you are calling

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

Upvotes: 3

Sachu
Sachu

Reputation: 7766

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

Upvotes: 4

Related Questions