locked
Razor Pages Entity Framework RRS feed

  • Question

  • User-190697402 posted

    Hi 

    Need one urgent help,

    I have a Users page which i have created using Razor Pages Entity Framework.

    Im using two dropdownlist and one radiobutton in that page.The issue im facing is whenever i submit the form its showing validation error for these three input fields.

    And also i dont know how to populate the selected value for dropdownlist and radiobutton in edit screen .

    Here with im attaching my code,please help me to figure it out.

    Models/Users.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.ComponentModel.DataAnnotations;
    
    namespace Contractor_HRMS.Models
    {
        public class Users
        {
    		public Guid ID { get; set; }	
    
    		[Required(ErrorMessage = "Please enter Username")]
    		[Display(Name = "Username")]
    		public string username { get; set; }
    
    		[Required(ErrorMessage = "Please enter Password")]
    		[Display(Name = "Password")]
    		[DataType(DataType.Password)]
    		public string userpassword { get; set; }
    
    		[Required(ErrorMessage = "Please enter First Name")]
    		[Display(Name = "First Name")]
    		public string firstname { get; set; }
    
    		[Required(ErrorMessage = "Please enter Last Name")]
    		[Display(Name = "Last Name")]
    		public string lastname { get; set; }
    
    		[Required(ErrorMessage = "Please select User Role")]
    		[Display(Name = "User Role")]
    		public string userrole { get; set; }
    
    		[Required(ErrorMessage = "Please enter Email Address")]
    		[Display(Name = "Email Address")]
    		public string emailaddress { get; set; }
    
    		[Required(ErrorMessage = "Please select Location")]
    		[Display(Name = "Location")]
    		public string Location { get; set; }
    
    		[Required(ErrorMessage = "Please select Status")]
    		[Display(Name = "Status")]
    		public string status { get; set; }
    	}
    }
    

    Pages/Admin/Users/Create.cshtml

    @page
    @model Contractor_HRMS.CreateModel
    
    @{
        ViewData["Title"] = "Create New User";
        Layout = "~/Pages/Shared/_Layout.cshtml";
    }
    
    <h4>CREATE NEW USER</h4>
    
    
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form method="post">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <!-- USER NAME -->
                <div class="form-group">
                    <label asp-for="Users.username" class="control-label"></label>
                    <input asp-for="Users.username" class="form-control" />
                    <span asp-validation-for="Users.username" class="text-danger"></span>
                </div>
    
                <!-- USER PASSWORD -->
                <div class="form-group">
                    <label asp-for="Users.userpassword" class="control-label"></label>
                    <input asp-for="Users.userpassword" class="form-control" />
                    <span asp-validation-for="Users.userpassword" class="text-danger"></span>
                </div>
    
                <!-- FIRST NAME -->
                <div class="form-group">
                    <label asp-for="Users.firstname" class="control-label"></label>
                    <input asp-for="Users.firstname" class="form-control" />
                    <span asp-validation-for="Users.firstname" class="text-danger"></span>
                </div>
    
                <!-- LAST NAME -->
                <div class="form-group">
                    <label asp-for="Users.lastname" class="control-label"></label>
                    <input asp-for="Users.lastname" class="form-control" />
                    <span asp-validation-for="Users.lastname" class="text-danger"></span>
                </div>
    
                <!-- USERROLE -->
                <div class="form-group">
                    <label asp-for="Users.userrole" class="control-label"></label>
                    <select asp-for="Users.userrole" name="userroles" asp-items="Model.userroles" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.userrole" class="text-danger"></span>
                </div>
    
                <!-- EMAIL ADDRESS-->
                <div class="form-group">
                    <label asp-for="Users.emailaddress" class="control-label"></label>
                    <input asp-for="Users.emailaddress" class="form-control" />
                    <span asp-validation-for="Users.emailaddress" class="text-danger"></span>
                </div>
    
                <!-- LOCATION -->
                <div class="form-group">
                    <label asp-for="Users.Location" class="control-label"></label>
                    <select asp-for="Users.Location" name="location" asp-items="Model.ContractorLocation" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.Location" class="text-danger"></span>
                </div>
    
                <!-- STATUS -->
                <div class="form-group">
                    <label asp-for="Users.status" class="control-label"></label><br/>
                    @foreach (var userStatus in Model.status)
                    {
                        <input type="radio" class="radio-inline" style="margin-left:2px;" asp-for="userStatus" value="@userStatus" />@userStatus
                    }
                    <span asp-validation-for="Users.status" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>
    
    <div>
        <a asp-page="Index">Back to List</a>
    </div>
    
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }
    

    Pages/Admin/Users/Create.cshtml.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Contractor_HRMS.Data;
    using Contractor_HRMS.Models;
    
    namespace Contractor_HRMS
    {
        public class CreateModel : PageModel
        {
            private readonly Contractor_HRMS.Data.ApplicationDbContext _context;
    
            public CreateModel(Contractor_HRMS.Data.ApplicationDbContext context)
            {
                _context = context;
            }
    
            [BindProperty]
            public Users Users { get; set; }
    
            //UserRole
            [BindProperty]
            public UserRole UserRole { get; set; }
            public SelectList userroles { get; set; }
    
            //Location
            [BindProperty]
            public Location Location { get; set; }
            public SelectList ContractorLocation { get; set; }
    
            [BindProperty]
            public string userStatus { get; set; }
            public string[] status = new[] { "Active", "InActive"};
       
    
            public IActionResult OnGet()
            {
                ContractorLocation = new SelectList(_context.Location.OrderBy(e => e.location), "locationCode", "location");
                userroles = new SelectList(_context.UserRole.OrderBy(e => e.userroles), "ID", "userroles");
                return Page();
            }
    
            
    
            // To protect from overposting attacks, enable the specific properties you want to bind to, for
            // more details, see https://aka.ms/RazorPagesCRUD.
            public async Task<IActionResult> OnPostAsync()
            {
                if (!ModelState.IsValid)
                {
                    return Page();
                }
    
                _context.Users.Add(Users);
                await _context.SaveChangesAsync();
    
                return RedirectToPage("./Index");
            }
        }
    }
    

    Tuesday, November 3, 2020 7:54 AM

Answers

  • User1312693872 posted

    Hi,teenajohn1989

    I'm sorry for making things be complicated. Using foreign key can be helpful if you want to get the UserRole Model's data such as role's name

    through Users. But  if you just want to add role to Users, then you do not need to use foreign key. So forget about the UserRoleID, just use one

    userrole property in Users to get the data:

    public class Users
        {
    ....
    		[Required(ErrorMessage = "Please select User Role")]
    		[Display(Name = "User Role")]
    		public string userrole { get; set; }
    
    		[Required(ErrorMessage = "Please select Location")]
    		[Display(Name = "Location")]
    		public string Location { get; set; }
    	}

    The UserRole Model just be used to set the role data: Highlighted Data is the property's data passed to Users.userrole, another one is used to

    show the data.

    showUserRoles = new SelectList(_context.UserRole.OrderBy(e => e.UserRoles), "UserRoles", "UserRoles");
    ContractorLocation = new SelectList(_context.Location.OrderBy(e => e.location), "location", "location");

    And then (delete name=.. in your first version)

    <div class="form-group">
                    <label asp-for="Users.userrole" class="control-label"></label>
                    <select asp-for="Users.userrole" asp-items="@Model.showUserRoles" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.userrole" class="text-danger"></span>
                </div>
    <!-- LOCATION -->
                <div class="form-group">
                    <label asp-for="Users.Location" class="control-label"></label>
                    <select asp-for="Users.Location" asp-items="Model.ContractorLocation" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.Location" class="text-danger"></span>
                </div>

    Result:

    Hope this time you can solve your problem.

    Best Regards,

    Jerry Cai

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 5, 2020 8:22 AM

All replies

  • User475983607 posted

    I recommend reading the following blog which illustrates how to populate and model bind selects in ASP.NET Core.

    https://www.learnrazorpages.com/razor-pages/forms/select-lists

    https://www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper

    Tuesday, November 3, 2020 1:25 PM
  • User-190697402 posted

    Hi mgebhard,

    Thanks for your response.

    By Referring the above tutorial only i implemented the dropdownlist.

    How can i use this dopdownlist concept in Entity Framework. When im submitting the form its showing validation errors.

    Do i need to edit my Model?Because there i have never used selectlist .Please advice me.

    Wednesday, November 4, 2020 2:40 AM
  • User1312693872 posted

    Hi,teenajohn1989

    teenajohn1989

    Im using two dropdownlist and one radiobutton in that page.The issue im facing is whenever i submit the form its showing validation error for these three input fields.

    And also i dont know how to populate the selected value for dropdownlist and radiobutton in edit screen .

    I made a demo for you , about how to show validatation, and show select list with the radio, then add them to database, you can check it:

    .cs:

    public class CreateModel : PageModel
        {
            private readonly MyDbContext _context;
    
            public CreateModel(MyDbContext context)
            {
                _context = context;
            }
    
            [BindProperty]
            public User Users { get; set; } 
    
            public SelectList showuserroles { get; set; }
    
            [BindProperty]
            public string userStatus { get; set; }
            public string[] status = new[] { "Active", "InActive" };
    
    
            public IActionResult OnGet()
            {
                showuserroles = new SelectList(_context.UserRole.OrderBy(e => e.userroles),"RoleID", "userroles");
                return Page();
            }
    
            public async Task<IActionResult> OnPostAsync()
            {
                if (!ModelState.IsValid)
                {
                    return Page();
                }
                _context.Users.Add(Users);
                await _context.SaveChangesAsync();
                return RedirectToPage("./Create");
            }
        }

    .cshtml:

    <div class="row">
        <div class="col-md-4">
            <form method="post">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                
                <!-- USERROLE -->
                <div class="form-group">
                    <label asp-for="Users.UserRole" class="control-label"></label>
                    <select asp-for="Users.RoleID"   //then don't use name=***
                            asp-items="@Model.showuserroles" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.RoleID" class="text-danger"></span>
                </div>
             
                <div class="form-group">
                    <label asp-for="Users.status" class="control-label"></label><br />
                    @foreach (var userStatus in Model.status)
                    {
                        <input type="radio" class="radio-inline" style="margin-left:2px;" asp-for="Users.status" value="@userStatus" />@userStatus
                    }
                    <span asp-validation-for="Users.status" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>

    Model:

    public class User
        {
    		public int ID { get; set; }
    
    		[Required(ErrorMessage = "Please select Status")]
    		[Display(Name = "Status")]
    		public string status { get; set; }
    
    		public int RoleID { get; set; }
    		public UserRole UserRole { get; set; }   //UserRole is here, as a navigation property
    
    	}
    
    public class UserRole
        {
            [Key]
            [Required(ErrorMessage = "Please select User Role")]
            [Display(Name = "User Role")]
            public int RoleID { get; set; }
    public string userroles { get; set; } }

    Result:

    Best Regards,

    Jerry Cai

    Wednesday, November 4, 2020 5:15 AM
  • User-190697402 posted

    Hi,

    Thank you so much Jerry!

    I will try this out and let you know the result.

    Wednesday, November 4, 2020 5:51 AM
  • User-190697402 posted

    Hi Jerry,

    I'm getting this error

    SqlException: Invalid column name 'UserRoleID'.

    My Users table structure is

    CREATE TABLE Users(
    	ID int IDENTITY(1,1) PRIMARY KEY,
    	username nvarchar(100) NOT NULL,
    	userpassword nvarchar(100) NULL,
    	firstname nvarchar(100) NOT NULL,
    	lastname nvarchar(100) NOT NULL,
    	userrole nvarchar(100) NOT NULL,
    	emailaddress nvarchar(100) NOT NULL,
    	Location nvarchar(100) NOT NULL,
    	status nvarchar(100) NOT NULL
    	);

    My column name in Users table is userrole not UserRoleID, so i have changed in Users.cs file like this

    		public string userrole { get; set; }
    		public UserRole UserRole { get; set; }

    and in Create.cshtml

    <!-- USERROLE -->
                <div class="form-group">
                    <label asp-for="Users.UserRole" class="control-label"></label>
                    <select asp-for="Users.userrole" asp-items="@Model.showUserRoles" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.UserRole" class="text-danger"></span>
                </div>

    Create.cshtml.cs

     showUserRoles = new SelectList(_context.UserRole.OrderBy(e => e.UserRoles), "UserRoleID", "UserRoles");

    The User Role table structure is like this

    CREATE TABLE UserRole (
        UserRoleID int IDENTITY(1,1) PRIMARY KEY,
    	UserRoles varchar(50)
    );

    But i dont understand why that error is showing?

    Wednesday, November 4, 2020 9:51 AM
  • User1312693872 posted

    Hi,teenajohn1989

    My demo can work, you can copy and try my code to make a comparison, if can't find the reason, you can copy your code to me because I can't

    know where you define that 'UserRoleID'.

    Best Regards,

    Jerry Cai

    Wednesday, November 4, 2020 10:05 AM
  • User-190697402 posted

    Hi Jerry,

    I have already posted my code snippets in above post along with my database table structure for both Users and UserRole. Do you want me to sent the entire file?

    I compared your code,the only difference i can see is, you have used UserRoleID in Users.cs file and your Users table has UserRoleID column.For me the column name is UserRoles,which is of string datatype. So i changed in Users.cs file accordingly.Still im getting UserRoleID error.

    I dont understand why it is so.Please help me to figure it out.

    Thanks,

    Teena John

    Thursday, November 5, 2020 1:07 AM
  • User1312693872 posted

    Hi,teenajohn1989

    The UserRoleID in the User.cs (My model name is 'User' because if I use 'Users', it has a conflict with the folder 'Admin/Users') is a foreign key of the Model 'UserRole', no matter it is string or int , make sure they can find each other by the foreign key.

    public class User
        {
    		public int ID { get; set; }
    		[Required(ErrorMessage = "Please select Status")]
    		[Display(Name = "Status")]
    		public string status { get; set; }
    		public int UserRoleID { get; set; }
    		public UserRole UserRole { get; set; }
    	}
    public class UserRole
        {
            [Key]
            [Required(ErrorMessage = "Please select User Role")]
            [Display(Name = "User Role")]
            public int UserRoleID { get; set; }
            public string userroles { get; set; }
        }

    And the two properties in the following code should be the two properties in UserRole.cs:

     showuserroles = new SelectList(_context.UserRole.OrderBy(e => e.userroles), "UserRoleID", "userroles");

    Then in Create.cshtml, asp-for targets the UserRoleID,the foreign key, used to pass the data. 

    <div class="form-group">
                    <label asp-for="Users.UserRole" class="control-label"></label>
                    <select asp-for="Users.UserRoleID"
                            asp-items="@Model.showuserroles" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.UserRoleID" class="text-danger"></span>
                </div>

    Then In your offered code, the Users.cs does not have a foreign key, you can change the public string userrole to public int UserRoleId, then

    the two Models can find each other. 

    Best Regards,

    Jerry Cai

    Thursday, November 5, 2020 1:40 AM
  • User-190697402 posted

    Hi Jerry,

    Still im getting the same error,

    Here im pasting my entire code with folder structure

    1)Models/Users.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.ComponentModel.DataAnnotations;
    
    namespace Contractor_HRMS.Models
    {
        public class Users
        {
    		public Guid ID { get; set; }	
    
    		[Required(ErrorMessage = "Please enter Username")]
    		[Display(Name = "Username")]
    		public string username { get; set; }
    
    		[Required(ErrorMessage = "Please enter Password")]
    		[Display(Name = "Password")]
    		[DataType(DataType.Password)]
    		public string userpassword { get; set; }
    
    		[Required(ErrorMessage = "Please enter First Name")]
    		[Display(Name = "First Name")]
    		public string firstname { get; set; }
    
    		[Required(ErrorMessage = "Please enter Last Name")]
    		[Display(Name = "Last Name")]
    		public string lastname { get; set; }
    
    		public int UserRoleID { get; set; }
    		public UserRole UserRole { get; set; }
    
    		[Required(ErrorMessage = "Please enter Email Address")]
    		[Display(Name = "Email Address")]
    		public string emailaddress { get; set; }
    
    		[Required(ErrorMessage = "Please select Location")]
    		[Display(Name = "Location")]
    		public string Location { get; set; }
    
    		[Required(ErrorMessage = "Please select Status")]
    		[Display(Name = "Status")]
    		public string status { get; set; }
    	}
    }
    

    2)Models/UserRole.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Contractor_HRMS.Models
    {
        public class UserRole
        {
            [Key]
    [Required(ErrorMessage = "Please select User Role")]
    [Display(Name = "User Role")] public int UserRoleID { get; set; } public string UserRoles { get; set; } } }

    3)Pages/Admin/Users/Create.cshtml(This on was added as Scaffolded Item)

    @page
    @model Contractor_HRMS.CreateModel
    
    @{
        ViewData["Title"] = "Create New User";
        Layout = "~/Pages/Shared/_Layout.cshtml";
    }
    
    <h4>CREATE NEW USER</h4>
    
    
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form method="post">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <!-- USER NAME -->
                <div class="form-group">
                    <label asp-for="Users.username" class="control-label"></label>
                    <input asp-for="Users.username" class="form-control" />
                    <span asp-validation-for="Users.username" class="text-danger"></span>
                </div>
    
                <!-- USER PASSWORD -->
                <div class="form-group">
                    <label asp-for="Users.userpassword" class="control-label"></label>
                    <input asp-for="Users.userpassword" class="form-control" />
                    <span asp-validation-for="Users.userpassword" class="text-danger"></span>
                </div>
    
                <!-- FIRST NAME -->
                <div class="form-group">
                    <label asp-for="Users.firstname" class="control-label"></label>
                    <input asp-for="Users.firstname" class="form-control" />
                    <span asp-validation-for="Users.firstname" class="text-danger"></span>
                </div>
    
                <!-- LAST NAME -->
                <div class="form-group">
                    <label asp-for="Users.lastname" class="control-label"></label>
                    <input asp-for="Users.lastname" class="form-control" />
                    <span asp-validation-for="Users.lastname" class="text-danger"></span>
                </div>
    
                <!-- USERROLE -->
                <div class="form-group">
                    <label asp-for="Users.UserRole" class="control-label"></label>
                    <select asp-for="Users.UserRoleID" asp-items="@Model.showUserRoles" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.UserRole" class="text-danger"></span>
                </div>
    
                <!-- EMAIL ADDRESS-->
                <div class="form-group">
                    <label asp-for="Users.emailaddress" class="control-label"></label>
                    <input asp-for="Users.emailaddress" class="form-control" />
                    <span asp-validation-for="Users.emailaddress" class="text-danger"></span>
                </div>
    
                <!-- LOCATION -->
                <div class="form-group">
                    <label asp-for="Users.Location" class="control-label"></label>
                    <select asp-for="Users.Location" name="location" asp-items="Model.ContractorLocation" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.Location" class="text-danger"></span>
                </div>
    
                <!-- STATUS -->
                <div class="form-group">
                    <label asp-for="Users.status" class="control-label"></label><br/>
                    @foreach (var userStatus in Model.status)
                    {
                        <input type="radio" class="radio-inline" style="margin-left:2px;" asp-for="userStatus" value="@userStatus" />@userStatus
                    }
                    <span asp-validation-for="Users.status" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>
    
    <div>
        <a asp-page="Index">Back to List</a>
    </div>
    
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }
    

    4)Pages/Admin/Users/Create.cshtml.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Contractor_HRMS.Data;
    using Contractor_HRMS.Models;
    
    namespace Contractor_HRMS
    {
        public class CreateModel : PageModel
        {
            private readonly Contractor_HRMS.Data.ApplicationDbContext _context;
    
            public CreateModel(Contractor_HRMS.Data.ApplicationDbContext context)
            {
                _context = context;
            }
    
            [BindProperty]
            public Users Users { get; set; }
    
            //UserRole        
            public SelectList showUserRoles { get; set; }
    
            //Location
            [BindProperty]
            public Location Location { get; set; }
            public SelectList DHLLocation { get; set; }
    
            [BindProperty]
            public string userStatus { get; set; }
            public string[] status = new[] { "Active", "InActive"};
       
    
            public IActionResult OnGet()
            {
                ContractorLocation = new SelectList(_context.Location.OrderBy(e => e.location), "locationCode", "location");
                showUserRoles = new SelectList(_context.UserRole.OrderBy(e => e.UserRoles), "UserRoleID", "UserRoles");
                return Page();
            }
    
            
    
            // To protect from overposting attacks, enable the specific properties you want to bind to, for
            // more details, see https://aka.ms/RazorPagesCRUD.
            public async Task<IActionResult> OnPostAsync()
            {
                if (!ModelState.IsValid)
                {
                    return Page();
                }
    
                _context.Users.Add(Users);
                await _context.SaveChangesAsync();
    
                return RedirectToPage("./Index");
            }
        }
    }
    

    Users Table Structure(I dont have UsersRoleID column in this table,im using userrole column)

    CREATE TABLE Users(
    	ID int IDENTITY(1,1) PRIMARY KEY,
    	username nvarchar(100) NOT NULL,
    	userpassword nvarchar(100) NULL,
    	firstname nvarchar(100) NOT NULL,
    	lastname nvarchar(100) NOT NULL,
    	userrole nvarchar(100) NOT NULL,
    	emailaddress nvarchar(100) NOT NULL,
    	Location nvarchar(100) NOT NULL,
    	status nvarchar(100) NOT NULL
    	);

    UserRole Table Structure

    CREATE TABLE UserRole (
        UserRoleID int IDENTITY(1,1) PRIMARY KEY,
        UserRoles varchar(50)
    );

    could you please tell me where im doing mistake.

    Thursday, November 5, 2020 2:39 AM
  • User1312693872 posted

    Hi,teenajohn1989

    First, your Users table does not corresponding with your model. If you changed your model, you should update your database too.

    I copied your model, and rebuild the database, then I find there is an error in status, change the code to the following.

    Now it works again. If anything wrong again, feel free to contact me. 

    <!-- STATUS -->
                <div class="form-group">
                    <label asp-for="Users.status" class="control-label"></label><br />
                    @foreach (var userStatus in Model.status)
                    {
                        <input type="radio" class="radio-inline" style="margin-left:2px;" asp-for="Users.status" value="@userStatus" />@userStatus
                    }
                    <span asp-validation-for="Users.status" class="text-danger"></span>
                </div>

    Best Regards,

    Jerry Cai

    Thursday, November 5, 2020 3:02 AM
  • User-190697402 posted

    Hi Jerry,

    Thank you so much for your patience and time.

    Im sorry,still having that issue.

    I added the Users folder as a Scaffolded Item.So after creating the Users Model file i have given the below code snippets

    Add-Migration InitialCreate
    Update-Database
    

    Users table is created automatically in my Database.

    Where as UserRole table i have created manually.

    After updating the Users Model file with this code snippet

    public int UserRoleID { get; set; }
    public UserRole UserRole { get; set; }

    i updated the database by typing Update-Database in Nuget Package Manager Console.

    Do i need to add UserRoleID column in my Users Table.

    Thursday, November 5, 2020 4:11 AM
  • User-190697402 posted

    Hi Jerry,

    i have created two new columns UserRoleID and LocationID in my Users Table.

    And Values are inserting properly(UserRole Id and Location Id are inserting)Now my pbm is ,

      1)How can i display the selected value in Edit Screen.

      2)My Users Listing page displays the ID of UserRoles and Location. How can display the respective values.

    Need help!

    Thursday, November 5, 2020 8:21 AM
  • User1312693872 posted

    Hi,teenajohn1989

    I'm sorry for making things be complicated. Using foreign key can be helpful if you want to get the UserRole Model's data such as role's name

    through Users. But  if you just want to add role to Users, then you do not need to use foreign key. So forget about the UserRoleID, just use one

    userrole property in Users to get the data:

    public class Users
        {
    ....
    		[Required(ErrorMessage = "Please select User Role")]
    		[Display(Name = "User Role")]
    		public string userrole { get; set; }
    
    		[Required(ErrorMessage = "Please select Location")]
    		[Display(Name = "Location")]
    		public string Location { get; set; }
    	}

    The UserRole Model just be used to set the role data: Highlighted Data is the property's data passed to Users.userrole, another one is used to

    show the data.

    showUserRoles = new SelectList(_context.UserRole.OrderBy(e => e.UserRoles), "UserRoles", "UserRoles");
    ContractorLocation = new SelectList(_context.Location.OrderBy(e => e.location), "location", "location");

    And then (delete name=.. in your first version)

    <div class="form-group">
                    <label asp-for="Users.userrole" class="control-label"></label>
                    <select asp-for="Users.userrole" asp-items="@Model.showUserRoles" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.userrole" class="text-danger"></span>
                </div>
    <!-- LOCATION -->
                <div class="form-group">
                    <label asp-for="Users.Location" class="control-label"></label>
                    <select asp-for="Users.Location" asp-items="Model.ContractorLocation" class="form-control">
                        <option value="">Please Select</option>
                    </select>
                    <span asp-validation-for="Users.Location" class="text-danger"></span>
                </div>

    Result:

    Hope this time you can solve your problem.

    Best Regards,

    Jerry Cai

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 5, 2020 8:22 AM
  • User-190697402 posted

    Hi Jerry,

    Thank you so much for your support and patience.

    The problem is solved now.

    Thursday, November 5, 2020 9:28 AM