Reputation: 4385
I have a div element in my index.cshtml with id #myresults and i am trying to load data through jquery.load method by calling a mvc controller method. But i am not able to get the right syntax.
I am passing a custom object as a parameter as well.
var mycustomObject = {
obj1:value1,
obj2:value2,
..
}
The following does not work...(an i have tried other combinations as well..i get server not found error)
$("#myresults").load ('@Url.Action("MyActionMethod","Home")',mycustomObject);
while the following works
$("#myresults").load('/Home/MyActionMethod', mycustomObject);
While the last statement works, it works only on localhost.
Whats the right syntax to use for jquery load with Url.Action ?
Upvotes: 1
Views: 6335
Reputation:
@Url.Action()
will always generate the correct url, so if your getting a 404, it means this code is in an external script file. Razor code is not executed in external scripts so your url would literally be the text "@Url.Action("MyActionMethod","Home")".
Options to solve this include
var url =
'@Url.Action("MyActionMethod","Home")';
an in the external file use
$("#myresults").load(url, mycustomObject);
assign the url to an element as a data-*
attribute, for example
<button type="button" id="loadSomething" data-url="@Url.Action("MyActionMethod","Home")">...</button>
,and in
the external file
$('#loadSomething').click(function() {
var url = $(this).data('url');
$("#myresults").load(url, mycustomObject);
});
Upvotes: 3
Reputation: 2583
Define the div element as:
<div id="myresults" onload="loadMyData();"></div>
And make the ajax call in your method:
<script type="text/javascript">
function loadMyData() {
$.ajax({
cache: false,
url: '@Html.Raw(Url.Action(MyActionMethod","Home"))',
data: { obj1:value1, obj2:value2 },
dataType: "json",
type: 'post',
success: function (result) {
if (result.success) {
$('#myresults').html(result.data);
}
else {
alert("Failed to load data!");
}
}
});
}
</script>
Upvotes: 2