简体   繁体   中英

asp.net MVC routing eror 404

i dont understand the rooting in ASP.net ; im missing something with this ? this is my root :

 routes.MapRoute(
                name: "ChampionID",
                url: "Champion/ChampionById/id",
                defaults: new { controller = "Champion", action = "ChampionById", id = "5" }
            );

this is my Controler :

public class ChampionController : Controller
{
    public ActionResult ChampionById(string x)
    {
        ChampionId ch = new ChampionId();
        ch.Id = x;
        return View(ch);
    }

if you can help me with this i will be thankful

Forget routes.MapRoute. Just wire up all routes and then put the route as an attribute like this:

public class ChampionController : Controller
{
    [Route("Champion/ChampionById/{id}")]
    public ActionResult ChampionById(string id)
    {
       ChampionId ch = new ChampionId();
       ch.Id = id;
       return View(ch);
    }
}

Also x should be id. Then just remove routes.MapRoute. Then make sure you have a corresponding cshtml file called ChampionById.

Change your route to below to fit you ActionResult like below:

routes.MapRoute(
                name: "ChampionID",
                url: "Champion/ChampionById/{id}",
                defaults: new { controller = "Champion", action = "ChampionById", id = UrlParameter.Optional }
            );

Note what I have updated with 'id'

Here all requests with 'Champion/ChampionById/' pattern will be mapped to this route and any thing after 'Champion/ChampionById/' will be the 'id parameter'. Since it is marked as optional on the route this can be null too. So better check for it.

public class ChampionController : Controller
{
    public ActionResult ChampionById(string id)
    {
        ChampionId ch = new ChampionId();

        if( !string.IsNullOrEmpty(id))
        { 
            ch.Id = id;
            return View(ch);
        }
        //<TODO> : handle when your id parameter is null
        return View(ch);
    }

edit your route.

routes.MapRoute(
                name: "ChampionID",
                url: "Champion/ChampionById/{x}",
                defaults: new { controller = "Champion", action = "ChampionById", x = UrlParameter.Optional }
            );

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