Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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?

share|improve this question
1  
call the javascript inside the main view where partial view is rendering –  Sachu May 27 at 9:26
1  
Put in in the main view and wrap it in document.ready –  Stephen Muecke May 27 at 9:27

3 Answers 3

up vote 1 down vote accepted

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})
share|improve this answer

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);   
        }
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.