Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 355
user2906420 Avatar asked Dec 20 '13 16:12

user2906420


People also ask

Can we call JavaScript function from controller in MVC?

There is no direct way to call JavaScript function from Controller as Controller is on Server side while View is on Client side and once the View is rendered in Browser, there is no communication between them.

Where do I put JavaScript code in MVC?

The recommended approach is to put in a separate JavaScript file or inside a section defined in Layout page. A section can be added in the MVC Layout page using @RenderSection() directive. For example, we can define a section in Layout page under <head> tag for scripts like below.

Can you use JavaScript in MVC?

The MVC architecture is very useful in JavaScript as it offers more than allowing developers to create modular code. For instance, since the Model in MVC returns data without formatting, the same components can be called for use in different interfaces. This allows for code reusability.


1 Answers

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
like image 132
Informitics Avatar answered Oct 11 '22 07:10

Informitics