Search code examples
c#.netrazor-pages

Model variable bool from html radiobutton


I'm new to .NET Core 5 and I've got a question.

Is it possible to somehow connect html input (for example from radio bootstrap input) with bool variable in Razor pages model? And also, how can I "print" variable on website? Because this way #Model.Logical doesn't work.

Example: C# Class Model

public class Logical
{
    public string logicalAtrr { get; set; }
}

cshtml.cs:

public class logicalModel : PageModel
{
    public Logical logical { get; set; }

    public void OnGet()
    {
    }

cshtml

@page
@model ...
@{}

<div class="form-check">
    <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1" asp-for="logical.logicalAtrr" value="true">
    <label class="form-check-label" for="flexRadioDefault1">
        True/False
    </label>

    <p>@Model.logical</p>
</div>

I'm really sorry if that question is wrong but I try to figure this Razor Pages concept and Web Development from scratch

Also, when I try to give [BindProperty] above the Logical class I've got an error:

Error CS0592 Attribute 'BindProperty' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.

I'm really be very thankful for any help


Solution

  • I would use a checkbox for a simple true/false option. If you use radios, you need to provide two - one for each state. You cannot deselect a single radio.

    The checkbox should be bound to a Boolean property. Model binding will take care of ensuring the the correct value is assigned on the server.

    public class Logical
    {
        public bool LogicalAttr { get; set; }
    }
    

    There is no need to set name, id or value attributes on input tag helpers. Razor Pages takes care of that. Just assign the property to the asp-for attribute:

    <input asp-for="Logical.LogicalAttr" class="form-check-input" />
    

    The BindProperty attribute should be assigned to the public PageModel property declaration:

    public class LogicalModel : PageModel
    {
        [BindProperty]
        public Logical Logical { get; set; }
    
        public void OnGet()
        {
        }
    

    It cannot be applied to the class, so this won't work and will raise the compiler error you referred to:

    [BindProperty]
    public class Logical
    {
       ...
    

    More reading here (my site, btw):
    Checkboxes: https://www.learnrazorpages.com/razor-pages/forms/checkboxes
    Radios: https://www.learnrazorpages.com/razor-pages/forms/radios
    Model Binding: https://www.learnrazorpages.com/razor-pages/model-binding