Search code examples
c#htmlasp.net-core

.NET Core Radio Button Binding to Bool


I have a radio button to select which of these 'ShipViaDetails' is default (IsDefault)

public class ShipViaDetails
{
    public string ShipCode { get; set; } = string.Empty;
    public bool HasAccess { get; set; }
    public bool IsDefault { get; set; }
}

When I submit to my controller the IsDefault is not being set correctly:

<td>
    <input type="radio"
           name="IsDefault"
           value="@svias.ShipViaAccesses[i].ShipCode"
    @(svias.ShipViaAccesses[i].IsDefault ? "checked" : "")
           hx-post="@url"
           hx-trigger="change"
           hx-target="this" />
</td>

How am I correctly supposed to create this radio button?


Solution

  • You need a list to correctly bind the properties to the model instance, your html looks like you do initialized a data list. Since you provided no controller code, here is a sample for you to refer to.

    ShipViaDetailsController.cs

    public class ShipViaDetailsController : Controller
    {
        private static List<ShipViaDetails> ShipViaAccesses = new List<ShipViaDetails>
        {
            new ShipViaDetails { ShipCode = "101", HasAccess = true, IsDefault = false },
            new ShipViaDetails { ShipCode = "102", HasAccess = true, IsDefault = true },
            new ShipViaDetails { ShipCode = "103", HasAccess = false, IsDefault = false }
        };
    
        public IActionResult Index()
        {
            return View(ShipViaAccesses);
        }
    
        [HttpPost]
        public IActionResult SetDefault(string selectedShip)
        {
            foreach (var ship in ShipViaAccesses)
            {
                ship.IsDefault = ship.ShipCode == selectedShip;
            }
    
            return RedirectToAction("Index");
        }
    }
    

    }

    Index.cshtml

    <form asp-action="SetDefault" method="post">
        <table>
            <thead>
                <tr>
                    <th>ShipCode</th>
                    <th>Default</th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < svias.Count; i++)
                {
                    <tr>
                        <td>@svias[i].ShipCode</td>
                        <td>
                            <input type="radio"
                                   name="SelectedShip" 
                                   value="@svias[i].ShipCode" 
                                   @(svias[i].IsDefault ? "checked" : "") 
                            />
                        </td>
                    </tr>
                }
            </tbody>
        </table>
        <button type="submit">Save Default</button>
    </form>
    

    enter image description here