0

So I am a little confused as to how to handle some MVC Routing

I have an AdminController

    public class AdminController : Controller
{
    //
    // GET: /Admin/

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

    public ActionResult Users()
    {
        return View();
    }
    public ActionResult Books()
    {
        return View();
    }

}

Which works fine. So I can go to /Admin/Books

This is the admin menu for managing books. Now in there I'd like to be able to route like

/Admin/Books/ViewBook/10
or
/Admin/Books/Add

Something like that. I can't seem to grasp how to route these things that way. I made a controller

AdminBookController

   public class AdminBooksController : Controller
{
    //
    // GET: /AdminBooks/
    public ActionResult List()
    {
        return View();
    }

    public ActionResult Add()
    {
        return View();
    }
    [HttpGet]
    public ViewResult BookDetails(Guid guid)
    {
        return View();
    }
    [HttpPost]
    public ViewResult BookDetails(ModifyBook Book)
    {
        if (ModelState.IsValid)
            return View("Book successfully Edited!");
        else
            return View();
    }
}

}

but I don't want it to be /AdminBooks I feel like /Admin/Books/Action/Param is much nicer.

Thanks in Advance!

0

3 Answers 3

2

If you want those urls to map to your AdminBooks controller, you'll need to map the following routes (in this order):

// maps /Admin/Books/ViewBook/{id} to AdminBooksController.BookDetails(id)
routes.MapRoute(
    "AdminBooks_ViewBook", // Route name
    "Admin/Books/ViewBook/{id}", // URL with parameters
    new { controller = "AdminBooks", action = "BookDetails", id = UrlParameter.Optional } // Parameter defaults
);

// maps /Admin/Books/{action}/{id} to AdminBooksController.{Action}(id)
routes.MapRoute(
    "AdminBooks_Default", // Route name
    "Admin/Books/{action}/{id}", // URL with parameters
    new { controller = "AdminBooks", action = "List", id = UrlParameter.Optional } // Parameter defaults
);

Note: be sure to put these mappings before the default MVC route.

Sign up to request clarification or add additional context in comments.

Comments

1

Consider creating an Admin Area and adding a BookController to that Area. See the following link for a walkthrough:

http://msdn.microsoft.com/en-us/library/ee671793.aspx

Comments

0

You can add a new route in your Global.asax file.

See this question:

Use MVC routing to alias a controller

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.