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.

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@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.
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
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.

4 Comments

Yes Porta but how does it execute the JS function automatically when partial view is loaded
The mapInit(@(Viewbag.locpoints)); is a call to your method. So once this code is loaded into the browser, it executes it.
tried it does not work - nothing appears when partial view is loaded.
For what I've read in another post (and experienced myself), you cannot use sections in partial views. They simple don't work
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" })

Comments

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

Comments

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
            }
        });
}

1 Comment

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
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.