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<Branch> 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
my issue on view step number 4 How to get values from userModel.Branches
on view on drop down list
My issue on view step number 4 How to get values from userModel.Branches on view on drop down list
Based on your shared code snippet, you all need to extract your _db.Branch.ToList()
into a SelectList and finally in asp-items Select Tag Helper bind the value.
Let's have a look in practice:
AddUser.cshtml.cs:
public void OnGet()
{
userModel.Branches = _db.Branches.ToList();
ViewData["Branches"] = new SelectList(_db.Branches.ToList(), "iBranchCode", "vBranchDesc");
}
AddUser.cshtml:
@page
@model RazorPageDemoApp.Pages.AddUserModel
<div class="form-group">
<label asp-for="@Model.userModel.Branches" class="control-label"></label>
<select class="form-control" name="iBranchCode" asp-items="ViewBag.Branches"></select>
<span asp-validation-for="@Model.userModel.Branches" class="text-danger"></span>
</div>
Note: Only, <select class="form-control" name="iBranchCode" asp-items="ViewBag.Branches"></select>
would also work.
Output:
Note: If you would like to know more details on Select Tag Helper you could check our official document here