How to set radio button to be checked by default

Viewed 1761

I'm implementing asp.net core 3.1. I have three radio buttons in my razor view and with the following code, I want to send the selected radio button value to Index action in controller in order to show its related data. My problem is, I can't set one of those radio buttons to be checked by default.

@model CSD.ChartObjects
 <form method="post">
        @foreach (var year in Model.Years)
        {
            <input type="radio" asp-for="Year" value="@year" />@year<br />
        }
        <input type="submit" asp-action="Index" />
    </form>

Here is my model object that is read in razor

public class ChartObjects
    {
        public List<ChartModel> Percent { get; set; }
        public List<ChartModel> Time { get; set; }
        public List<ChartModel> Avg { get; set; }
        public List<ChartModel> Total { get; set; }


        public string Year { get; set; }
        public string[] Years = new[] { "1398", "1399", "1400" };
    
}

And here is the body of my HomeController:

[HttpGet]
        public IActionResult Index()
        {
            return (BuildIndexModel("1399"));
        }

        [HttpPost]
        public IActionResult Index([FromForm] string currentYear)
        {
            return (BuildIndexModel(currentYear));
        }



        public IActionResult BuildIndexModel(string currentYear)
        {
...
}
3 Answers

I think this will work:

@foreach (var year in Model.Years)
{
    var fi = (year == Model.Years[0]) ? true : false ;
    <input type="radio" asp-for="Year" value="@year" checked="@fi" />@year<br />
}

My problem is, I can't set one of those radio buttons to be checked by default.

To set a default checked radio button, you can try following code snippet.

<form method="post">
    @foreach (var year in Model.Years)
    {
        <input type="radio" asp-for="Year" value="@year" checked="@(year == Model.Years.FirstOrDefault() ? "checked" : null)"/>@year<br />
    }
    <input type="submit" asp-action="Index" />
</form>

Update:

my data by default is for 1399

You can pass default year through ViewData, like below.

In controller action

ViewData["defaultyear"] = "1399";

In view page

<input type="radio" asp-for="Year" value="@year" checked="@(year == ViewData["defaultyear"].ToString() ? "checked" : null)"/>@year<br />
Related