Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return View(model: MyModel); equivalent in ASP.Net Core Razor Pages

I expected to see something like return Page(model: MyModel); in ASP Razor Pages. instead the Page(); has no parameter.

So I can return Pages which does not have PageModel class.

I cant use TempData as MyModel is a complex type.

How do I get the same functionality we have with ASP MVC return View(model: MyModel);

Please, The question is not for all MVC developers but experienced ASP.Net Core Razor Page developers. Thank you.

like image 934
Nellymandela Avatar asked Oct 20 '25 18:10

Nellymandela


1 Answers

Ok here is an example from a simple Restaurant app. As you can see the Restaurant object is a property inside the DetailModel. Once i set it inside the OnGet() method. I am able to access its data inside my Razor Page View.

public class DetailModel : PageModel
{
    private readonly IRestaurantData restaurantData;

    [TempData]
    public string Message { get; set; }

    public Restaurant Restaurant { get; set; }

    public DetailModel(IRestaurantData restaurantData)
    {
        this.restaurantData = restaurantData;
    }

    public IActionResult OnGet(int restaurantId)
    {
        Restaurant = restaurantData.GetById(restaurantId);
        if(Restaurant == null)
        {
            return RedirectToPage("./NotFound");
        }
        return Page();
    }
}

and the view from the page.

@page "{restaurantId:int}"

@model MyProject.Pages.Restaurants.DetailModel
@{
    ViewData["Title"] = "Detail";
}

<h2>@Model.Restaurant.Name</h2>
<div>
    Id: @Model.Restaurant.Id
</div>
<div>
    Location: @Model.Restaurant.Location
</div>
<div>
    Cuisine: @Model.Restaurant.Cuisine
</div>

@if(Model.Message != null)
{
    <div class="alert alert-info">@Model.Message</div>
}

<a asp-page="./List" class="btn btn-default">All Restaurants</a>

Really Razor pages work as one so you do not have to return the Model. You just bind it and you have access inside the page.

Does this makes sense? Please also read the DOCS for more information: https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&tabs=visual-studio

like image 131
panoskarajohn Avatar answered Oct 23 '25 07:10

panoskarajohn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!