简体   繁体   中英

Basic MVC routing (amibigous route issue)

I have 3 actions on my controller, none of which should have a route apart from their parameters.

[Route("")]
[HttpGet]
public ActionResult Index()
{
// List of things
    return View();
}

[Route("")]
[HttpGet]
public ActionResult Detail(int id)
{
// Specific 'thing'
    return View();
}

[Route("")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Detail(MyViewModel myViewModel)
{
// 'Thing' has just been posted
    return View();
}

I get a 'call is ambiguous' error when trying to call the first, a 404 on the second (ie "/area/1001"). How must I configure my routes here?

I'd like to hit

  • Index() with '/area/'
  • Detail(int id) with '/area/123' and
  • Detail(MyViewModel myViewModel) with a post to '/area/'

EDIT

I know I can add [Route("{id:int}")] to the second action, but not sure about the third.

[RoutePrefix("Area")]
public AreaController : Controller {
    //GET Area
    [Route("")]
    [HttpGet]
    public ActionResult Index() {
        // List of things
        return View();
    }

    //GET Area/123
    [Route("{id:int}")]
    [HttpGet]
    public ActionResult Detail(int id) {
        // Specific 'thing'
        return View();
    }

    //POST Area
    [Route("")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Detail(MyViewModel myViewModel) {
        // 'Thing' has just been posted
        return View();
    }
}

make sure you have attribute routing configured

public static void RegisterRoutes(RouteCollection routes) {

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapMvcAttributeRoutes();

    //...other code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM