0

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?

0

2 Answers 2

0

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

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

1 Comment

It seems a editor mistooked the correction, I'm working with Razor Pages.
0

Thanks for your kind reply.
My problem was resolved thanks to your support.
In my case, I had to send a custom model to a view like this:

public class MyInfo
{
    public string Title {get;set;}
    public List<string> Messages {get;set;}
}

Therefore, I wrote it like below:

Index.cshtml:

public IActionResult OnGet()
{
    MyInfo info = new(){ Title = "title" };
    info.Add("my message");
    
    ViewData["info"] = info;
    return new ViewResult() { ViewName = "InfoView", ViewData = this.ViewData };
}

InfoView.cshtml:

@{
    MyInfo info = (MyInfo)ViewData["info"];
}
<h2>@info.Title</h2>
@foreach(var msg in info.Messages)
{
    <div>@msg</div>
}

I am very grateful for your support!

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.