\\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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With