Calling the home controller action using ajax
I have an 'Index' action within my home controller which responds to the url '/'. The action also has an optional 'id' parameter...
[HttpGet]
public ViewResultBase Index(int id = -1)
{
....
}
the routing for this is...
routes.MapRoute("Home",
"",
new { controller = "Home", action = "Index", id = -1 } );
If I try to call this action using ajax...
$.get(
'@Url.Action("Index", "Home")',
{ id: 20 },
function (response) {
});
the call fails as the url is /?id=20
Is it possible to force the Url.Action to include the controller and action names, as when I do this...
'@Url.Action("Index", "Home")' + 'Home/Index'
all works fine, or do I need to correct my routing?
You dont need to make a special route for your Action method like so. The default route:
{controller}/{action}/{id},
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
Handles that case already; when you request '/' on your server, you should get sent to your Home/Index
action method. You should remove the custom route you have specified and let the default route send you to the correct destination.
上一篇: 如何使用MapRoute,使用ActionLink()?
下一篇: 使用ajax调用主控制器操作