Search code examples
c#asp.net-corerazor-pages

How to display another view in ASP.NET Core Razor Pages


I'm trying to display the another view in a current page.

In ASP.NET MVC (running on the full/classic .NET framework), it was possible like this:

return View("view name", MyModel);

As the method of ASP.NET Core, I found this article:

How to return a different view with object in Razor Pages?

Here's its alternative method.

return new RedirectToPageResult("view", MyModel);

However, the first method does not change the URL in the address bar, while the following method does change the URL.

Does anyone know how to do it in ASP.NET Core MVC without changing the url?


Solution

  • The method return View("view name", MyModel); also exist in asp.net core

    And infact, the two methods you've shown are not the same

    RedirectToPageResult returns a redirect to the destination as below(the url changed because it send another request with the url you've seen to the server )

    enter image description here

    return View("viewname", model); returns a view which uses a model to render HTML(it returns 200 with the html codes in response body).

    For more details you could check this document

    And you mentioned Razor Page in your titile but in the end of your question,you mentioned ASP.NET Core MVC,it may help if you could specifc which you are working with

    In ASP.NET Core MVC project,you could try with return View("view name", MyModel); directly

    In Razor Page project , I tried as below:

    public IActionResult OnGet()
            {
                ViewData["SomeKey"] = "SomeValue";            
                return new ViewResult() { ViewName = "SomePage" ,ViewData=this.ViewData};
            }
    

    Add a Razor View(Not Razor Page) named SomePage in Pages folder

    enter image description here

    the codes in view:

    @ViewData["SomeKey"]
    

    Result:

    enter image description here