How to show checked radio button in Razor edit view Asp net core mvc
As far as I know, the checked="checked"
attribute is set because the current value of those radio buttons are equal to model value (the property you're assigned in asp-for
attribute inside tag helper). Hence, your current setup with asp-for="@item.Value"
is wrong here:
<input asp-for="@item.Value" type="radio" value="@item.Value" />
If you want to set their values based on Selected
property inside SelectListItem
instance, you need to use a property from your viewmodel class into asp-for
attribute (the property must defined as value type or string).
Below is a proper example setup:
Model
// Viewmodel class
public class ViewModel
{
// used to store selected value in select tag helper
public string SelectedValue { get; set; }
public List<SelectListItem> OptionList { get; set; }
}
Controller action
// Populate select list
[HttpGet]
public IActionResult Change()
{
var model = new ViewModel();
model.OptionList = new List<SelectListItem>();
// populate list values here
model.OptionList.Add(new SelectListItem { Text = "1001", Value = "Vilnius", Selected = true });
model.OptionList.Add(new SelectListItem { Text = "1002", Value = "Trakai", Selected = false });
return View(model);
}
View
@* Set viewmodel property into tag helper *@
@model ViewModel
<form asp-controller="Manage" asp-action="Change" method="post">
@foreach (var item in Model.OptionList)
{
<br />
<input asp-for="SelectedValue" type="radio" value="@item.Value" /> @(item.Value + " - " + item.Text)
}
<br />
<input type="submit" value="OK" />
</form>
Related issue:
Radio Button Tag Helper sets every radio button to checked
Related videos on Youtube
user1855805
Updated on June 04, 2022Comments
-
user1855805 almost 2 years
Despite of Asp net core code in Razor view:
@model List<SelectListItem> <form asp-controller="Manage" asp-action="Change" method="post"> @foreach (SelectListItem item in Model) { <br /> <input asp-for="@item.Value" type="radio" value="@item.Value" /> @(item.Value + " - " + item.Text) } <br /> <input type="submit" value="OK" /> </form>
all radio buttons are checked in browser -> view source
<input type="radio" value="1001" checked="checked" id="item_Value" name="item.Value" /> 1001 - Vilnius<br /> <input type="radio" value="1002" checked="checked" id="item_Value" name="item.Value" /> 1002 - Palanga<br />
How it can be all radio buttons checked?
Added:
var lst = new List<SelectListItem>() { new SelectListItem { Value = "1001", Text = "Vilnius", Selected = true }, new SelectListItem { Value = "1002", Text = "Trakai", Selected = false } };
-
Tetsuya Yamamoto about 5 yearsCan you provide what kind of
List<SelectListItem>
passed to view? I think it's not a good idea to haveList<SelectListItem>
for@model
directive.
-
-
Sayed Mahmoud over 2 yearsAll radio button has checked!