简体   繁体   中英

How to create few url in one controller use .net Core

I work with ASP .NET core, and I have issues.

I have 3 pages which can be created in one controller, but for this pages I must have just one controller and in this conroler, I must have a function which will create separate URL for this 3 pages .

For example:

* http://mydomain/page/ *Home, Load, Blog;

For this, I need have navigation, but I will have the same HTML file only will data change from the model.

So I will have 3 navigation button which will navigate user for same page but another content which I will receive from the model, and from controller I just need change page URL.

How I can do this?

You don't want to repeat the HTML? Use one view. And then you can have a controller like this snippet:

class PagesController : Controller
{
    [HttpGet("about")]
    public IActionResult About() => View("MyCommonView", yourModel); // get the model from wherever you plan to

    [HttpGet("contact")]
    public IActionResult Contact() => View("MyCommonView", yourModel);

    [HttpGet("whateverelse")]
    public IActionResult WhateverElse() => View("MyCommonView", yourModel);
}

It's possible to just have one action, but I wouldn't do that. I'd instead have separate views per action, and put the markup that's common for the three actions layout file. That will give the different actions more flexibility.

One of the way is to decorate your action with Route attribute:

[Route("page")]
public class PagesController : Controller
{
    // you may also use [HttpGet("{pageName}", Name = "PagePath")] instead,
    // to explicitly match HTTP GET requests
    [Route("{pageName}", Name = "PagePath")]
    public IActionResult GetPage(string pageName)
    {
        switch(pageName?.ToLower())
        {
            case "home":
                return View("Page", homeModel);
            case "home":
                return View("Load", loadModel);
            case "home":
                return View("Blog", blogModel);
            default:
                return NotFound();
        }
    }
}

Now you can create your view at Views/Pages/Page.cshtml and generate links with helpers:

@Url.RouteUrl("PagePath", new { pageName = "Home" }) <!-- will produce "/page/Home" string -->

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