简体   繁体   中英

.Net MVC Controller different route name using the same cshtml as view

In .NET MVC, I see it always follows this naming convention: RouteName in the controller and it is a view called 'RouteName.cshtml'.

My question is how can I use SAME cshtml file with different RouteName?

The default View() method defaults to matching the Action name, but you can use the View(string) method to specify that path to your desired CSHTML, like in the following example:

// in action method that is *not* RouteName
return View("RouteName");

You can re-use chunks of CSHTML with partials ; depending on the problem that you're trying to solve, this may be a better solution.

Can you edit your question and add more context? Why do you need to render the same cshtml from more than one ActionResult method? What are you trying to accomplish?

For example, you have a view named About.cshtml You have 2 action methods and both of them are using About.cshtml

So you can try

public ActionResult Index()
        {
        var model = "view model";
        // Pass view model as the second parameter
        return View("About", model);
        }

public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            // Not need pass view name because view name and action method name are same (About
            return View();
        }

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