Home > Software design >  How to conditionally redirect to a page based on Radio Button Selection in ASP.NET Core Razor Pages?
How to conditionally redirect to a page based on Radio Button Selection in ASP.NET Core Razor Pages?

Time:11-04

I'm new in ASP.NET Core Razor Pages. I've built a simple solution with a template from Visual Studio 2010 and ASP.NET Core application

I've added a radio button of two options to the login page refering to sex selection. I want to conditionally return the RedirectionToPage depending on the selected option in the radio Button.

IF USER SELECTS BOY add password and email --> Redirects to "./boysNames" page

IF USER SELECTS GIRL add password and email --> Redirects to "./girlsNames" page

This is my code:

Radio Buttons in login page

   <div class="form-group ">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1" checked>
                        <label class="form-check-label" for="inlineRadio1">Boy</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2">
                        <label class="form-check-label" for="inlineRadio2">Girl</label>
                    </div>
                </div>

Login Model : PageModel

//using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
//using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
//using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace LuckyHandApp.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class LoginModel : PageModel
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly ILogger<LoginModel> _logger;

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

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

        [BindProperty, Required]
        public string SexSelection { get; set; }




        public IList<AuthenticationScheme> ExternalLogins { get; set; }

        public string ReturnUrl { get; set; }

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

    

        public class InputModel
        {
            [Required]
            [EmailAddress]
            public string Correo { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Contraseña { get; set; }

            [Display(Name = "Recordar contraseña")]
            public bool RememberMe { get; set; }
        }

        public async Task OnGetAsync(string returnUrl = null)
        {
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ModelState.AddModelError(string.Empty, ErrorMessage);
            }

            returnUrl ??= Url.Content("~/");

            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            ReturnUrl = returnUrl;
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true  lockoutOnFailure: false
                var result = await _signInManager.PasswordSignInAsync(Input.Correo, Input.Contraseña, Input.RememberMe, lockoutOnFailure: false); //I Think I have to add here the radio selection
                if (result.Succeeded)
                {
                    _logger.LogInformation("BoysSelection.");
                    return RedirectToPage("./boysNames");
                }
                else
                {
                     _logger.LogInformation("Girls Selection.");
                    return RedirectToPage("./girlsNames");
                   
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
    }
}

CodePudding user response:

You can try to get value of radio button in Pagemodel,and if value is option1,return RedirectToPage("./boysNames");,if value is option2,return RedirectToPage("./girlsNames");. Here is a demo:

view:

    <form method="post">
        <div class="form-group ">
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1" checked>
                <label class="form-check-label" for="inlineRadio1">Boy</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2">
                <label class="form-check-label" for="inlineRadio2">Girl</label>
            </div>
        </div>
       
           ...

        <input type="submit" value="submit"/>
    </form>

pagemodel(The value of radio button will be binded to inlineRadioOptions):

[BindProperty]
    public string inlineRadioOptions { get; set; }
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true  lockoutOnFailure: false
                var result = await _signInManager.PasswordSignInAsync(Input.Correo, Input.Contraseña, Input.RememberMe, lockoutOnFailure: false); //I Think I have to add here the radio selection
                if (result.Succeeded)
                {
                    if (inlineRadioOptions == "option1")
                    {
                         _logger.LogInformation("BoysSelection.");
                         return RedirectToPage("./boysNames");
                    }
                    else {
                          _logger.LogInformation("Girls Selection.");
                          return RedirectToPage("./girlsNames");
                   
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
  • Related