This is my controller,
public ActionResult ReturnMethodTest(int id)
{
string name = "John";
return Json( new {data=name});
}
I am trying to get data from this controller by using code below but I am getting .
Can you please tell me what am I doing wrong?
$.ajax({
url: @Url.Action("ReturnMethodTest", "HomeController"),
data: {
id: 5,
},
success: function (data) {
console.log(data);
}
});
This is my controller,
public ActionResult ReturnMethodTest(int id)
{
string name = "John";
return Json( new {data=name});
}
I am trying to get data from this controller by using code below but I am getting .
Can you please tell me what am I doing wrong?
$.ajax({
url: @Url.Action("ReturnMethodTest", "HomeController"),
data: {
id: 5,
},
success: function (data) {
console.log(data);
}
});
Share
Improve this question
edited May 19, 2016 at 2:37
Michael Gaskill
8,04210 gold badges39 silver badges44 bronze badges
asked Jul 13, 2015 at 6:54
Da ArtagnanDa Artagnan
1,1994 gold badges18 silver badges28 bronze badges
2
|
3 Answers
Reset to default 53@Url.Action
only returns the action url's string, without quotes around it.
You'll need to wrap that url in quotes.
Replace:
url: @Url.Action("ReturnMethodTest", "HomeController"),
With:
url: '@Url.Action("ReturnMethodTest", "HomeController")',
// ^ ^
Otherwise, the file returned to the client will contain:
url: /HomeController/ReturnMethodTest,
Which isn't valid JS, nor what you want. The replacement gives the following result:
url: '/HomeController/ReturnMethodTest',
Which is a perfectly valid JavaScript string.
A Javascript regular expression literal looks like this -- a pattern enclosed between slashes:
var re = /pattern/flags;
If you interpolate a variable that begins with a slash but do not put quotation marks around it, it will be interpreted as a regular expression, not a string. Another time this comes up is with JSP expression language, where you should write the first, not the second:
var spinner = "<img src='${contextPath}/images/ajax-loader-small.gif'>"
var spinner = "<img src='" + ${contextPath} + "/images/ajax-loader-small.gif'>"
Please remove the Controller
suffix while specifying in url
.
Try it this way:
url: '@Url.Action("ReturnMethodTest", "Home")'
url: '@Url.Action("ReturnMethodTest", "HomeController")'
– Umesh Sehta Commented Jul 13, 2015 at 6:55