I've been through many questions about this same issue and even browsed the RadiobuttonFor helpers source code but I just can't get my head around this seemingly very simple issue.
The problem is, the generated input-element (type radio) from RadioButtonFor-helper will not have the checked-attribute even though the value is in the model. I'm using Asp.Net MVC 5.2.3.
I have a simple example of the problem here: Model:
public class MyModel
{
public string Name { get; set; }
[UIHint("Gender")]
public string Gender { get; set; }
public MyModel(string name, string gender)
{
Name = name;
Gender = gender;
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
Models.MyModel defaultModel = new Models.MyModel("Jack", "M");
return View(defaultModel);
}
}
The thing is, everything works fine if I don't use an EditorTemplate ie:
@Html.EditorFor(m => m.Name)
<label>
@Html.RadioButtonFor(m => m.Gender, "M")
Male
</label>
<label>
@Html.RadioButtonFor(m => m.Gender, "F")
Female
</label>
Result:
But when I use an EditorTemplate for the Gender the checked-attribute will not be there:
"Parent view"
@Html.EditorFor(m => m.Name)
@Html.EditorFor(m => m.Gender)
EditorTemplate (in ControllerName/EditorTemplates/Gender.cshtml-file)
@model String
<label>
@Html.RadioButtonFor(m => m, "M")
Male
</label>
<label>
@Html.RadioButtonFor(m => m, "F")
Female
</label>
Result:
<input class="text-box single-line" id="Name" name="Name" type="text" value="Jack">
<label>
<input id="Gender" name="Gender" type="radio" value="M">
Male
</label>
<label>
<input id="Gender" name="Gender" type="radio" value="F">
Female
</label>
Why is this and how should it be handled? I tried to browse the source code for RadioButtonFor and it should set the "isChecked" to true if model value and the radiobuttons value-parameter match. Even tried to debug the MVC source code but my Visual Studio was unable to download symbols for some reason :)
Any help appreciated.