MVC 5 Routing Attribute

岁酱吖の 提交于 2019-12-01 03:16:11

For Attribute Routing in ASP.NET MVC 5

decorate your controller like this

[RoutePrefix("Home")]
public HomeController : Controller {
    //GET Home/Index
    [HttpGet]
    [Route("Index")]
    public ActionResult Index() {
        return View(); 
    }
}

And enable it in route table like this

public class RouteConfig {

    public static void RegisterRoutes(RouteCollection routes) {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //enable attribute routing
        routes.MapMvcAttributeRoutes();

        //convention-based routes
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = "" }
        );
    }
}

Please check here for information on routing: http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs

Most likely, default routing should be something like below:

routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

Also, looks like the Index Action Method is missing a parameter, see below:

public ActionResult Index(string id)
        {
            return View();
        }

Try placing string id in your Index method.

Anubhav Sharma
public class URLRedirectAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
                string destinationUrl = "/VoicemailSettings/VoicemailSettings";
                filterContext.Result = new JavaScriptResult()
                {
                    Script = "window.location = '" + destinationUrl + "';"
                };
        }
    }

try changing the index action to this:

public ActionResult Index(int? id = null) 
{
  return View(); 
}

This should do the trick. So you can pass the id as a param with the "/{value}" or just use "/?id={value}"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!