简体   繁体   中英

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.

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.

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.

Try to call your controller via JQuery.

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

                //Do your stuffs here
            }
        });
}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM