Reputation: 14145
I have controller which accepts one argument from the view and it should return json data back to that same view.
on controller action I have
public ActionResult GetDataById(int id)
{
var data = ...give me data...
return Json(data, JsonRequestBehavior.AllowGet);
}
On the view I have
<ul id="#myList">
</ul>
(function () {
var updateList = function (competitions) {
$("#myList").html($("listTemplate").render(competitions))
.listview();
};
$(document).one("pageinit", function () {
var url = "/Home/GetDataById/1";
$.getJSON(url)
.then(updateList);
});
} ());
<script id="listTemplate" type="text/x-jsrender">
<li>
<a href="{{:Name}}">{{:Id}}
<span class="ui-li-count">{{:CountedData}}</span>
</li>
</script>
On debugging GetDataById is not hitted at all. When I put alert(url) before calling $.getJSON I'm getting correct url. What I'm doing wrong here?
Update: Route config is
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
namespaces: new[] { "MyWebApp.Controllers" },
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Upvotes: 0
Views: 1102
Reputation: 1820
I am using $.getJSON as described by Quite M. Porta's, but with a slight difference. I add a '/' to the end of the URL
$.getJSON("/Home/GetDataById/", { id: 1 }).then(updateList);
If all else fails, you could try that.
Upvotes: 1
Reputation: 18155
Just a wild guess, but are you running the site locally? If so is it in a virtual directory (i.e. do you go http://localhost/home/index
or http://localhost/mysite/home/index)
?
You could try this:
var url = @Url.Content( "~/Home/GetDataById/1" );
Upvotes: 1
Reputation: 9881
What would happen if you specify the Id as a parameter
var url = "/Home/GetDataById";
$.getJSON(url, { id: 1 })
Upvotes: 1