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

Time:11-16

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:

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 enter image description here

the codes in view:

@ViewData["SomeKey"]

Result:

enter image description here

CodePudding user response:

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!

  • Related