Click here to Skip to main content
15,741,581 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I worked on mvc razor pages . I face issue I can't pass data from page model to view

What I have tried:

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
        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
        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

 <div class="form-group row">
            <label for="branch-select" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">Branch</label>
            <div class="col-sm-3">
                <select id="branch-select" name="SelectedBranchId"  class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;">
                    <option value="">-- Select Branch --</option>
                    @foreach (var branch in Model.????)
                        <option value="@branch.iBranchCode">@branch.vBranchDesc</option>
Updated 4-May-23 22:58pm

1 solution

As far as I know, razor mvc have some HTML function helper.

Check this post, and follow instruction.

You do not need using foreach.

you can use ViewData['listOfBranch'] containing data of branches 81 data at your case.

usage to show select item :
<%= Html.DropDownList("SelectedItem", (IEnumerable<YourClassModel>)ViewData["listOfBranch"])%>
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900