If my solution is totally based on razor page and partial views then what is the flow to build in steps ?

mehmood tekfirst 771 Reputation points
2022-08-16T11:52:34.847+00:00

Hi,
If my application is based on razor pages then please mention the necessary steps .

How the route will work ?

In that case do I need to remove following route from program.cs?

app.MapControllerRoute(  
    name: "default",  
    pattern: "{controller=Home}/{action=Index}/{id?}");  

Currently , half of my logic is based conventional mvc controller and half is based in razor page.

Moreover, I have already added in Program.cs

builder.Services.AddControllersWithViews();  
  
builder.Services.AddRazorPages();  
  
app.UseRouting();  
app.MapControllerRoute(  
    name: "default",  
    pattern: "{controller=Home}/{action=ParamIndex}/{id?}");  
  
app.MapRazorPages();  

What are the other things if someone can show the example or working steps then it will be great.

I am getting this error

231499-image.png

thanks.

carIndex.cshtml

@page "/carindex"  
@inject IConfiguration Configuration  
@using CarRentalWidget.Models.ViewModels  
@model CarRentalWidget.Views.Home.ParamWidget.ParamPageModel  
@{  
    #region Code    
    string localUrl = @Configuration["CustomSettings:LocalUrl"];  
    #endregion  
}  
  
<div id="SearchVehiclePage">  
   @if (Model != null && Model.Data != null)  
    {  
        @await Html.PartialAsync("ParamSearchCar.cshtml",Model.Data)  
    }  


 public class ParamPageModel : PageModel  
    {  
        [BindProperty(SupportsGet = true)]  
        public string Path { get; set; } = "";  
  
        [BindProperty(SupportsGet = true)]  
        public string ApiKey { get; set; } = "";  
        [BindProperty]  
        public FranchiseWidgetSettingVM? Data { get; set; } = null!;  
        public void OnGet(string path, string apiKey)  
        {  
            Path = path;  
            ApiKey = apiKey;  
        }  
    }  

and Model always throw a null exception.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,201 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,141 Reputation points
    2022-08-18T13:44:01.043+00:00

    Post your source code in GitHub if you want/need a community code review.

    I created a test based on your source and passing parameter in the URL works as expected.

    var builder = WebApplication.CreateBuilder(args);  
      
    // Add services to the container.  
    builder.Services.AddControllersWithViews();  
      
    builder.Services.AddRazorPages();  
      
    var app = builder.Build();  
      
    // Configure the HTTP request pipeline.  
    if (!app.Environment.IsDevelopment())  
    {  
        app.UseExceptionHandler("/Error");  
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
        app.UseHsts();  
    }  
      
    app.UseHttpsRedirection();  
    app.UseStaticFiles();  
      
    app.UseRouting();  
      
    app.UseAuthorization();  
      
    app.MapControllerRoute(  
        name: "default",  
        pattern: "{controller=Home}/{action=ParamIndex}/{id?}");  
      
    app.MapRazorPages();  
      
    app.Run();  
    

    carindex.cshtml

    @page "/carindex"  
    @model RazorPagesWithMvc.Pages.carindexModel  
      
    <h1>Car Index</h1>  
      
    <div>Path = @Model.Path)</div>  
    <div>ApiKey = @Model.ApiKey)</div>  
      
    @{  
    }  
    

    carindex.cshtml.cs

    using Microsoft.AspNetCore.Mvc;  
    using Microsoft.AspNetCore.Mvc.RazorPages;  
      
    namespace RazorPagesWithMvc.Pages  
    {  
        public class carindexModel : PageModel  
        {  
      
            [BindProperty(SupportsGet = true)]  
            public string Path { get; set; } = "";  
      
            [BindProperty(SupportsGet = true)]  
            public string ApiKey { get; set; } = "";  
      
      
            public void OnGet()  
            {  
            }  
        }  
    }  
    

    URL

    https://localhost:7027/carindex/?path=some/path&apikey=123  
    
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Michael Taylor 48,736 Reputation points
    2022-08-16T14:22:35.23+00:00

    MapDefaultRoute is only needed if you need the routing engine to use a default route if it cannot find a match. If you're using Razor Pages or you attribute all your controllers then it isn't going to be used and can be removed. Personally I don't use it in any of my apps. But it doesn't hurt if you have it either way.

    As for your error you're reporting 2 different behaviors here so something isn't right. The screenshot shows a 404 which means the routing couldn't find anything to match the URL. Therefore none of your razor pages/controllers would get called. Yet you then say that your model is empty. If it isn't getting to your route then it wouldn't call any code so you wouldn't know the model was empty. So either there is more information you haven't provided yet or you're seeing 2 different problems.

    You mentioned that you also have controllers which probably explains why you have AddControllersWithViews as well. I'm assuming here that your razor pages are not conflicting with the controllers. If they are then the wrong code is getting called. Have you looked at the Visual Studio output window to see if the runtime is reporting any errors?

    For your code, the page works by itself in a standalone app which leads me to believe your issue is with your existing controllers. Note that you don't need params for OnGet as you're using the BindProperty to have it auto-bound. I wonder if your problem is with the other code you have in your HTML such as the customSettings.

       @page "/carindex"  
       @model RazorPagesApp.Pages.CarIndexModel  
       @{  
       }  
         
       <div id="SearchVehiclePage">  
           <p>Path = @Model?.Path</p>      
           <p>ApiKey = @Model?.ApiKey</p>  
       </div>  
    
    
    
       public class CarIndexModel : PageModel  
       {  
           [BindProperty(SupportsGet = true)]  
           public string Path { get; set; } = "";  
         
           [BindProperty(SupportsGet = true)]  
           public string ApiKey { get; set; } = "";  
           [BindProperty]  
           public string Data { get; set; } = "";  
         
           public void OnGet()  
           {       
           }  
       }  
    
    1 person found this answer helpful.
    0 comments No comments

  2. Bruce (SqlWork.com) 56,846 Reputation points
    2022-08-16T19:00:03.657+00:00

    actually your url is invalid. "/"s should not be in the query string. s/b:

    https://localhost:7177/carindex/?path=%2Flocations%2Fe%2Fsouth%2Fex%2F&apikey=fdf343434

    1 person found this answer helpful.