0

Edit 1: include full code related to this not just a portion.

I am trying to create username input validation for admin role on my application. I will start from the table in SQL server.

Employee table columns in SQL server has [ROWID],[ID],[LAST_NAME],[FIRST_NAME]...

Employee DB model

public class EmployeeModel
    {
        public int RowID { get; set; }
        [Key]
        public int ID { get; set; }
        public string First_Name { get; set; }
        public string Last_Name { get; set; }
    }

DB context

public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext (DbContextOptions<ApplicationDbContext> options) : base(options)
        { 
        }

        public DbSet<WorkOrderModel> WorkOrder { get; set; }
        public DbSet<CommentModel> Comment { get; set; }
        public DbSet<PostModel> Post { get; set; }
        public DbSet<ReplyModel> Reply { get; set; }
        public DbSet<ApplicationUser> ApplicationUser { get; set; }
        public DbSet<EmployeeModel> Employee { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder); //This is necessary if class is IdentityDbContext instead of DbContext
            modelBuilder.Entity<WorkOrderModel>().HasKey(c => new { c.Type, c.Base_ID, c.Lot_ID, c.Split_ID, c.Sub_ID });
        }
    }

My InputValidation controller is the controller that will only have remote validation logics in it. I am trying to build a logic that will validate if the user is in the table "Employee" using only [ID] and [FIRST_NAME].

Original code I had is as below.

if (_dbContext.Employee.Any(n => (n.First_Name + "." + n.ID.ToString().PadLeft(3, '0')) == userName) != true)
            {
                return Json(true);
            }

            return Json($"Employee does not exist.");

Then changed to below per suggestion by Tisa in a reply.

public class InputValidationController : Controller
    {
        private readonly ApplicationDbContext _dbContext;

        public InputValidationController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        [AcceptVerbs("GET", "POST")]
        public IActionResult IdVerification(string userName)
        {
            var allUserList = (from u in _dbContext.Employee
                               select new
                               {
                                   Name = u.First_Name + "." + u.ID.ToString().PadLeft(3, '0')
                               })
                               .ToList().Where(x => x.Name == userName);

            if (allUserList != null)
            {
                return Json(true);
            }
            return Json($"Employee does not exist.");
        }
    }

PageModel where input class is in.

public class ResetPasswordModel : PageModel
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly ILogger<ResetPasswordModel> _logger;


        public ResetPasswordModel(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, ILogger<ResetPasswordModel> logger)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        [TempData]
        public string StatusMessage { get; set; }

        public class InputModel
        {
            [Required]
            [Display(Name = "User Name [ First Name.### (Employee number) ]")]
            [Remote(action: "IdVerification", controller: "InputValidation")]
            public string UserName { get; set; }

            [Required]
            [StringLength(20, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [DataType(DataType.Password)]
            [Display(Name = "Confirm password")]
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
            public string ConfirmPassword { get; set; }

            //public string Code { get; set; }
        }
    ...
    }

Lastly the view page. SQL_Web_App is the name of the project and has UserRoles class.

@page
@model ResetPasswordModel
@using SQL_Web_App

@{
    ViewData["Title"] = "Reset password";
}

@if (User.IsInRole(UserRoles.AdminRole))
{
    <h1>@ViewData["Title"]</h1>
        <h4>Reset password for a user.</h4>
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Input.UserName"></label>
                <input asp-for="Input.UserName" class="form-control" />
                <span asp-validation-for="Input.UserName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.Password"></label>
                <input asp-for="Input.Password" class="form-control" />
                <span asp-validation-for="Input.Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.ConfirmPassword"></label>
                <input asp-for="Input.ConfirmPassword" class="form-control" />
                <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
            </div>
            <button type="submit" class="btn btn-primary">Reset</button>
            </form>
        </div>
    </div>
}

my statement before this edit 1

As you can see under the display of the `InputModel` the user name is "FirstName.EmployeeNumber", I am trying to match that input to `_dbContext.Employee.Any(n => n.First_Name + "." + n.ID.ToString().PadLeft(3, '0')` but I do not get any result for both != and ==.

Now I tried below for both == and != result goes to always not null in any case.

if (allUserList != null)
{
    Json(true);
}
return Json($"Employee does not exist.");

Please help me to see what I did wrong.

Thank you.

random name input but no validation message

1 Answers1

0

You can change the logic to this:

To get the Name in your code, you should use Model to accept it and then get the

UserName property.

public IActionResult IdVerification(InputModel input)
    {
        var username=input.UserName;
        var allUserList = (from u in _dbcontext.Employee
                           select new
                           {
                               Name = u.First_Name + "." + u.ID.ToString().PadLeft(3, '0')
                           })
                           .ToList();

        if (allUserList[0].Name==userName)
        {
            return Json(true);
        }
        return Json($"Employee does not exist.");
    }
Jerry Cai
  • 869
  • 1
  • 4
  • 4
  • Thank you for your input! but I found allUserList in the script is IEnumerable and is always not null. – NamelessCosmicDust Apr 23 '21 at 00:55
  • @NamelessCosmicDust What do you mean?If related name not exists, it will be null. Could you please share your detailed needs with code? – Jerry Cai Apr 23 '21 at 01:07
  • Hmm ok, I will share all not just a part of the codes like above. – NamelessCosmicDust Apr 23 '21 at 01:15
  • I edited my post to include all codes I have for this. – NamelessCosmicDust Apr 23 '21 at 02:03
  • @NamelessCosmicDust I have edit my answer, it will solve this. – Jerry Cai Apr 23 '21 at 02:16
  • With previous code allUserList was empty always and thought that was why it was not null. But that was my misunderstanding. Now `.Where(x => x.Name == userName)` removed I see allUserList gets employees in it. So I think the problem is the parameter "userName" is not getting the input and always null... – NamelessCosmicDust Apr 23 '21 at 03:33
  • @NamelessCosmicDust I have updated my answer, the reason is the name can not be bound, you can learn the model binding here:[Link](https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0) – Jerry Cai Apr 23 '21 at 05:24
  • Using `InputModel input` in the paramater works! Why learn.microsoft.com doesn't explain such? – NamelessCosmicDust Apr 24 '21 at 02:21
  • Having `allUserList[0].Name` always picked the first user from the list so I had to add `var user = allUserList.Where(n => n.Name == userName).ToList();` before if statement then changed if to `if (user.Count != 0)`. Putting `.Where(n => n.Name == userName)` inside `var allUserList = ...` did not have the same result. In my guess while the list is being created by combining `Name = u.First_Name + "." + u.ID.ToString().PadLeft(3, '0')` there is nothing matches to `userName`. – NamelessCosmicDust Apr 24 '21 at 02:49
  • This is an additional info for someone who may need this. This solution works for this case but I found that this cannot be used for other classess. I will need to find a solution for that but for now this will do. – NamelessCosmicDust Apr 29 '21 at 02:55