How to execute JavaScript function on PartialView load in MVC 3

user2906420 picture user2906420 · Dec 20, 2013 · Viewed 40.7k times · Source
\\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.

Answer

marteljn picture marteljn · Dec 20, 2013

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.