I worked on asp.net mvc razor pages . I face issue I can't pass data from page model to view
what i try
1- I create view model as
public class AddUserViewModel
{
public int SelectedBranchId { get; set; }
public List Branches { get; set; }
}
2-Branch Model
public class Branch
{
[Key]
public string iBranchCode { get; set; }
public string vBranchDesc { get; set; }
}
3 - on razor pages AddUser.cshtml.cs I get 81 rows on userModel.Branches
public class AddUserModel : PageModel
{
[BindProperty]
public AddUserViewModel userModel { get; set; }
private readonly ADCContext _db;
public AddUserModel(ADCContext db)
{
_db = db;
userModel = new AddUserViewModel();
}
public void OnGet()
{
userModel.Branches= _db.Branch.ToList();// from debug get 81 rows
//userModel.Branches have 81 rows
}
}
4 - on view AddUser.cshtml (main issue )
How to access userModel.Branches Branch List from page model to view
meaning How to fill (81 rows) on drop down list on view from data I received on page model
@page "/AddUser"
@model UC.ADC.Host.Pages.Users.AddUserModel
asp.net-mvcasp.net-core.net-corerazor-pages
Tuhin PaulPosted May 4, 2023, 3:13 AM
To access the userModel.Branches list in the view, you can use the foreach loop to iterate over the list and populate the dropdown list options. Here's an example:
We are accessing the userModel.Branches list using Model.userModel.Branches in the foreach loop. For each branch in the list, we create an option element with the branch code and description as the value and display text, respectively. We are also setting the name attribute of the dropdown list to SelectedBranchId, which matches the SelectedBranchId property in the AddUserViewModel. This allows the selected value to be bound to the model property when the form is submitted. Make sure to also add a [HttpPost] action method in the AddUserModel to handle the form submission and receive the selected branch ID.