Home > Back-end >  ASP.NET MVC add RememberMe checkbox to @model AuthenticationScheme[]
ASP.NET MVC add RememberMe checkbox to @model AuthenticationScheme[]

Time:06-15

Im trying to add a checkbox and handle the change event, i can post back to the controller if i do

 <input type="checkbox" name="RememberMe" checked="@ViewBag.RememberMe"  /> RememberMe

It always posts false, I don't know how to handle the change event or if/how to extend the @model AuthenticationScheme[] to include a RememberMe property

Controller

 [HttpPost("~/signin")]
        public async Task<IActionResult> SignIn([FromForm] string provider, bool rememberMe)
        {
            // Note: the "provider" parameter corresponds to the external
            // authentication provider choosen by the user agent.
            _serverStore.RememberMe = rememberMe;
            if (string.IsNullOrWhiteSpace(provider))
            {
                return BadRequest();
            }

            if (!await HttpContext.IsProviderSupportedAsync(provider))
            {
                return BadRequest();
            }
            if (User.Identity is not null && User.Identity.IsAuthenticated)
            {
                User? user = new()
                {
                    NameIdentifier = 0,
                    Email = string.Empty
                };
                long dbuserId = await CreateOrUpdateUser(user).ConfigureAwait(false);
                ClaimsIdentity? identity = User.Identity as ClaimsIdentity;
                identity?.AddClaim(new Claim("Id", dbuserId.ToString()));
                return Redirect("/");
            }
            return Challenge(new AuthenticationProperties { RedirectUri = "/Login", ExpiresUtc = DateTime.UtcNow.AddYears(1), IsPersistent = true, AllowRefresh = true, IssuedUtc = DateTime.Now, Items = { new KeyValuePair<string, string?>("MyId", "123456") } }, provider);
        }

View

@using Microsoft.AspNetCore.Authentication
@model AuthenticationScheme[]

<div >
    <h1>Authentication</h1>
    <p >Sign in using one of these external providers:</p>
   
    @foreach (var scheme in Model.OrderBy(p => p.DisplayName))
    {
         
        <form action="/signin" method="post">
            <input type="hidden" name="Provider" value="@scheme.Name" />
            <input type="hidden" name="ReturnUrl" value="@ViewBag.ReturnUrl" />
            @*<input type="checkbox" name="RememberMe" checked="@scheme."  onchange =@HandleRememberMeChange(a) /> RememberMe*@
            <button  type="submit">Connect using @scheme.DisplayName</button>
        </form>
    }
</div>

CodePudding user response:

Check-boxes in HTML5 are a bit peculiar in that they do not submit a value when they are unchecked.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-6.0#checkbox-hidden-input-rendering

If you use Input Tag Helpers for asp net core, this will resolve the issue (see documentation mentioned.

Alternatively you could add your own custom JavaScript which will change the value on change and it will only send to the server when checked (which will not be an issue as the server will give it a default which is false for booleans.

Here is a basic sample of HTML how you could achieve this functionality.

<body>
<form method="post">
    <input type="checkbox" name="RememberMe">Remember Me
    <input type="text" name="Username" placeholder="Username"> 
    <button type="submit">Send</button>
</form>
<script>
    var checkbox = document.querySelector('input[type="checkbox"]');
    checkbox.addEventListener('change', function(){
        if(checkbox.checked){
            checkbox.value = 'true';
        }else{
            checkbox.value = 'false';
        }
    });
</script>
  • Related