Search code examples
c#asp.net-corebindingradio-buttonrazor-pages

Binding a radiobutton to model


I have a radio button on a razorpage, like this

<input asp-for="Order.CostCenter" type="radio" id="proj" name="CostCenter" value="proj">
<label>Project</label>
<input asp-for="Order.CostCenter" type="radio" id="dep" name="CostCenter" value="dep">
<label>Department</label>

the model for the form look like this

 [BindProperty] public OrdPurchase Order { get; set; }

and the model for the SQL look like this

 public string CostCenter { get; set; }

and the data type for CostCenter in SQL is varchar(80)

when I save the form the CostCenter is not binded to any value in SQL, it stays as NULL, but the rest of the forms values saves correctly

what can be the cause of that?

I want to save the value "proj" if "proj" is selected, and "dep" if "dep" is selected

enter image description here

Thanks

Thomas


Solution

  • Asp.net core bind model data with name attribute.You only need to remove name="CostCenter",here is a demo: .cshtml:

    <form method="post">
        <input asp-for="Order.CostCenter" type="radio" id="proj"  value="proj">
        <label>Project</label>
        <input asp-for="Order.CostCenter" type="radio" id="dep" value="dep">
        <label>Department</label>
        <input type="submit" value="submit" />
    </form>
    

    .cshtml.cs:

     [BindProperty]
     public OrdPurchase Order { get; set; }
     public IActionResult OnPost()
            {
                return Page();
            }
    

    result: enter image description here