Erwin1 Erwin1 - 9 days ago 6
HTML Question

Load @Html.Action using Jquery

On my dashboard I have the following div which works fine and when the page is loaded the action return a view

<div id="result1" class="col-xs-2 col-sm-4">
@Html.Action("index", "Gauge1", new { p1 = 2025, p2 = 8, p3 = 101 })
</div>


How can I load the view generated from the
@Html.Action
into the
<div id = "result1"
when
(document).ready
in JQuery?

I tried this but it is not working.

<script type="text/javascript">
$(document).ready(function(){
$('#result1').load(@(Html.Action("index", "Gauge1", new { p1 = 2025, p2 = 8, p3 = 101 })));
});
</script>

<div id="result1" class="col-xs-2 col-sm-4">
</div>

Answer

The Url.Action helper method is used to generate urls. It generates a valid url by encoding all parameters.

So, in your example ampersand will be encoded and your url will look like this:

/Gauge1/index?p1=2025&amp;p2=8&amp;p3=101

In Razor every content using a @ block is automatically HTML encoded by Razor.

The Url.Action returns just a string so thats why the & gets encoded.

You need to use @Html.Raw to prevent the Encode of &.

Please try this:

<script type="text/javascript"> 
     $(document).ready(function(){
     var url = "@(Html.Raw(Url.Action("index","Gauge1", new { p1=2025, p2=8,p3=101})))";
     $('#result1').load(url);
</script>

<div id="result1" class="col-xs-2 col-sm-4">
</div>