1
votes

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.

1
you sould return a object that define in the function other wise {model: MyModel} - LDS
This question is essentially identical to your other question: stackoverflow.com/questions/59207419/… - Mike Brind

1 Answers

1
votes

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://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&tabs=visual-studio