简体   繁体   中英

Razor Pages OnGet Parameter

This is a follow-up question to this: How do I pass a parameter to RazorPage OnGet()?

The issue is that the Username string never makes it to the OnGet method.

I know I'm doing this wrong - hence why I am asking for help because I'm not sure what to do.

My issue is that my Index.cshtml page needs to call the OnGet() method which initializes at startup. (the link above only details how to pass the parameter via an anchor).

I created a public string property Username.

Then in my Index.cshtml file I defined the property before the Model was declared (I also tried after).

Index.cshtml.cs

public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public List<DisplayJob> Jobs { get; set; }
        public string Username { get; set; }

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            Console.WriteLine("username: " + Username);
            Jobs = DisplayJobService.GetListDisplayJobs(-1, 100, "", "", Username);
        }
    }

Index.cshtml

@page
@{
    ViewData["Username"] = "s32xckJ1";
    Model.Username = "s32xckJ1";
}
@model IndexModel
@{

    ViewData["Title"] = "Home page";
}
<p>Jobs Count: @Model.Jobs.Count()</p>

As you have discovered, as far as routing is concerned.

@page "{datestart}/{dateend}/{referenceid:int=0}/{client?}"

Might be an odd way but you can add an addtional root by using the AddPageRoute method.

services.AddMvc().AddRazorPagesOptions(options =>
{
   options.Conventions.AddPageRoute("/details", "{datestart}/{dateend}/{client?}");
});

Use Attribute [httpget] get parameter by viewmodel. for send to razor cshtml can use viewbag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM