Search code examples
asp.net-core.net-coreasp.net-core-7.0

asp-for does not work in my .NET 7 project


asp-for and asp-validation-for do not work for sending data and validation (on a Razor page on Mac OS).

credential.UserName is empty and credential.Password why all time is empty.

sapn text-danger not worked .

My system is Mac OS and ASP.NET Core 7 with Visual Studio 2022

UI :

<div class="container border" style="padding:20px">
    <form method="post">
        <div class="text-danger" asp-validation-summary="All"></div>
        <!-- UserName part Form -->
        <div class="mb-3 row">
            <div class="col-2">
                <label asp-for="credential.UserName"></label>
            </div>
            <div class="col-5">
                <input type="text" asp-for="credential.UserName" class="form-control" />
                <span class="text-danger" asp-validation-for="credential.UserName" ></span>
            </div>
        </div>
        <!-- Password part Form -->
        <div class="mb-3 row">
            <div class="col-2">
                <label asp-for="credential.Password"></label>
            </div>
            <div class="col-5">
                <input type="password" asp-for="credential.Password" class="form-control" />
                <span class="text-danger" asp-validation-for="credential.Password"></span>
            </div>
        </div>
        <!-- Submit Part Form -->
        <div class="mb-3 row">
            <div class="col-2">
                <input type="submit" class="btn btn-primary" value="Login" />
            </div>
            <div class="col-5">
                
            </div>
        </div>
    </form>
</div>

C# code:

namespace WebAppSecurity.Pages.Account
{
    public class LoginModel : PageModel
    {
        public Credential credential { get; set; } = new Credential();

        public void OnGet()
        {
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid) 
                return Page();

            // Verify the credentials
            if(credential.UserName == "admin" && credential.Password == "admin")
            {
                // Creating the security context
                var Claims = new List<Claim> 
                                 {
                                     new Claim(ClaimTypes.Name,"admin"),
                                     new Claim(ClaimTypes.Email, "[email protected]")
                                 };
                var identity = new ClaimsIdentity(Claims, "MyCookieAuth");

                ClaimsPrincipal claimsprincipal = new ClaimsPrincipal(identity);

                await HttpContext.SignInAsync("MyCookieAuth", claimsprincipal);

                return RedirectToPage("/Index");
            }

            return Page();
        }
    }

    public class Credential
    {
        [Required]
        [Display(Description = "User Name")]
        public string UserName { get; set; } = string.Empty;

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; } = string.Empty;
    }
}

program.cs:

builder.Services.AddAuthentication().AddCookie("MyCookieAuth", options =>
{
    options.Cookie.Name = "MyCookieAuth";
    options.LoginPath = "/Account/Login";
});

Solution

  • [BindProperty] attribute: Can be applied to a public property of a controller or PageModel class to cause model binding to target that property:

    Try to add [BindProperty]:

     [BindProperty]
     public Credential credential { get; set; } = new Credential();
    

    result:

    enter image description here

    Client-side validation prevents submission until the form is valid. The Submit button runs JavaScript that either submits the form or displays error messages.

    try to add script references after your form to support client-side validation:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.js"></script>
    

    result:

    enter image description here You can read [BindProperty] attribute and Client-side validation to know more.