user2906420
user2906420

Reputation: 1269

How to execute JavaScript function on PartialView load in MVC 3

\\code
public ActionResult mapPartial(DataTable dt)
        {
            string strEvents = "[";
            foreach (DataRow row in dt.Rows)
            {
                strEvents += "[" + row["Lat"].ToString() + ", " + row["Long"].ToString() + ", " + "\"" +
                row["LastName"].ToString() + row["DateOfBirth"].ToString() + "\"" + "],";
            }
            strEvents = strEvents.Remove(strEvents.LastIndexOf(","));
            strEvents += "]";

            ViewBag.locpoints = strEvents;

            return PartialView(dt);
        }

//in the partial view page
<script type="text/javascript">
       function mapInit(Viewbag.locpoints) {

              var arr = $.parseJSON(Viewbag.locpoints);
              //more code which assigns a map to div map below 
       }
</script>

<div id="map" class="map"></div>

How can i call the JS function immediately to render my map when the partial view is loaded. The partial method in the controller returns a string which is used as parameter in the JS function. Hope it makes sense.

Upvotes: 15

Views: 49047

Answers (6)

Informitics
Informitics

Reputation: 187

We have implemented a much simpler solution.

_Layout.cshtml after @RenderSection("scripts", required: false) (and Jquery,etc.)

<script>
    $(document).ready(function () { if (typeof partialScript !== "undefined") partialScript();});
</script>

Then, in your partial view:

<script type="text/javascript">
function partialScript() {
    alert("hi");
}
</script>

This ensures the following:

  • jQuery is loaded
  • All main view scripts are loaded
  • DOM is ready

Upvotes: 2

Shalin
Shalin

Reputation: 157

Consider using the onSuccess Ajax Option and wire up a javascript function where your jquery is written. For example you have following script written in your mainView that calls the partial View. Suppose you want do something when the anchor tag in your partial view is clicked

var fromPartial=function()
            {
                var v = $(this).closest("div");
                var mId = v.attr('id');
                if (mId == 'divDetail') {
                    event.preventDefault();
                    //what you want to achieve
                }
            }

Now in your partial view the anchor tag is created as shown below

           @Ajax.ActionLink("Select", "AssignSpeaker", new { 
        conferenceId = ViewBag.ConferenceId, sessionId = session.Id },
                                 new AjaxOptions() { HttpMethod="Get",
     InsertionMode= InsertionMode.Replace, UpdateTargetId="yourTarget",
 OnSuccess="fromPartial" })

Upvotes: 2

Gjohn
Gjohn

Reputation: 1281

The only way you can do this is by calling your controller action using JQuery and have it return your partial view. Use Jquery to update whatever section of the page the partial view goes to and then call the javascript method you want to render the map

Upvotes: 1

Andy T
Andy T

Reputation: 9881

After you define it, you just call it. However, it looks like you are including the MVC Viewbag values in the JS function definition. You should be passing those values when you call the JS method:

<script type="text/javascript">
       function mapInit(locPoints) {    
              var arr = $.parseJSON(locPoints);
              //more code which assigns a map to div map below 
       }
       mapInit(@(Viewbag.locpoints));
</script>

Note: This assumes you have jQuery loaded.

Upvotes: 3

Carlos Coelho
Carlos Coelho

Reputation: 586

Try to call your controller via JQuery.

$(document).ready(function () {
 $.ajax({
            type: 'GET',
            url: 'your_controller_url',
            success: function (data) {

                //Do your stuffs here
            }
        });
}

Upvotes: 1

marteljn
marteljn

Reputation: 6516

Since you appear to be using JQuery why not:

<script type="text/javascript">
       $(document).ready(function(){
              var arr = $.parseJSON("@Viewbag.locpoints");
              //more code which assigns a map to div map below 
       });
</script>

I also changed how you referenced your ViewBag value since the way you have it, it won't be be a string literal in JavaScript.

Also, as a side note consider using JSON serializer to convert your data into JSON. It is considered a bad practice to do it manually like you did above.

Upvotes: 4

Related Questions