Home > Blockchain >  Why does property gets nulled from view to code page
Why does property gets nulled from view to code page

Time:06-09

I have something like this (reduced for brevity)

Expenditures.cshtml.cs:

    public class Expenditures: PageModel {
        [BindProperty(SupportsGet = true)] public string PersonnelNo {get;set;}
        
        public async Task OnGetAsync() { //some code 
        }

        public async Task < IActionResult > OnPostAsync() {
            return Page();
          }
    }

and Expenditures.cshtml

@page
@using DataAccessLibrary.Models
@model WorkInProgress.Pages.Expenditures
@{
ViewData["Title"] = "Expenditures";
}
<h1>Project Information</h1>
<form method="post">
   <table >
      <thead class = "table-light">
         <tr>
            <th>@Model.PersonnelNo</th>
         </tr>
      </thead>
   </table>
   <div >
      @Html.HiddenFor(model => model.PersonnelNo, Model.PersonnelNo)
      <input type="submit" value="Save" />
   </div>
</form>

this works the first time, when the page loads (PersonnelNo in the .cs file has a value)

however when I press the submit button and I try to reload the same page, the value for PersonnelNo is nulled.

Is there a way to pass the parameter from the view back to the .cs file so it can be reused?

I thought the @Html.HiddenFor(model => model.PersonnelNo, Model.PersonnelNo) should do this, but is not working

CodePudding user response:

Below demo I can get the value, you can refer to it.

First way

Adding parameter to the handler method.

public class IndexModel : PageModel
    {
        [BindProperty(SupportsGet = true)]       
        public string PersonnelNo { get; set; }

        public async Task OnGetAsync()
        {
            PersonnelNo = "1";
        }
    
        public async Task<IActionResult> OnPostAsync(string PersonnelNo)
        {
            return Page();
        }
    }

View:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<h1>Project Information</h1>
<form method="post">
   <table >
      <thead class = "table-light">
         <tr>
            <th>@Model.PersonnelNo</th>
         </tr>
      </thead>
   </table>
   <div >
      @Html.HiddenFor(model => model.PersonnelNo, Model.PersonnelNo)
      <input type="submit" value="Save" />
   </div>
</form>

Result:

enter image description here

Second way

Add name attribute to do model binding

Add this line<input name="PersonnelNo" type="hidden" /> after @Html.HiddenFor(model => model.PersonnelNo, Model.PersonnelNo)

Result:

enter image description here

  • Related