15
\\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.

user2906420
  • 1,249
  • 6
  • 27
  • 44

6 Answers6

4

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.

marteljn
  • 6,446
  • 3
  • 30
  • 43
  • 4
    If this is in a partial, it probably was not loaded when the page was included, so the `$(document).ready()` method might have already executed by the time the partial was rendered. – Andy T Dec 20 '13 at 16:37
  • @QuetiM.Porta That is a good point. This only makes sense if it is consumed by a regular view and not via AJAX. Since it accepts a `DataTable` I don't know how it would be loaded via AJAX. – marteljn Dec 20 '13 at 16:40
  • I can also create the JSON code in partial view in razor but then after getting the JSON string how to call the JS function – user2906420 Dec 20 '13 at 16:49
3

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.

Andy T
  • 10,223
  • 5
  • 53
  • 95
2

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" })
Shalin
  • 157
  • 1
  • 6
2

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
1

Try to call your controller via JQuery.

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

                //Do your stuffs here
            }
        });
}
Carlos Coelho
  • 566
  • 1
  • 5
  • 14
  • Carlos in the above way the problem is the controller action takes a parameter which is the @model. I do not want to pass the model back to the action. there must be another way – user2906420 Dec 20 '13 at 17:17
1

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

Gjohn
  • 1,261
  • 1
  • 8
  • 12