Skip to content

RadioButtonFor doesn't resolve isChecked properly when nested in EditorTemplate #164

Closed
@brandondahler

Description

@brandondahler

Problem

When using RadioButtonFor and specifying a default expression of m => m, the checked attribute isn't set as expected.

While default expressions of m => m aren't generally used (or even valid at times, unless the call is nested under another model), they are distinctly valid and necessary in EditorTemplates when overriding a default template.

Example

Models/IndexModel.cs

namespace Test
{
    public class IndexModel
    {
        public bool? Boolean { get; set; }
    }
}

Controllers/HomeController.cs

namespace Test
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new IndexModel() { Boolean = true });
        }
    }
}

Views/Home/Index.cshtml

@model Test.Models.IndexModel


@Html.EditorFor(m => m.Boolean)

Views/Home/EditorTemplates/Boolean.cshtml

@Html.RadioButtonFor(m => m, true)
@Html.LabelFor(m => m, "True")

Expected Output

<input checked="checked" id="Boolean" name="Boolean" type="radio" value="True">
<label for="Boolean">True</label>

Actual Output

<input id="Boolean" name="Boolean" type="radio" value="True">
<label for="Boolean">True</label>

Possible Solution

I believe this is caused by the following line:

!String.IsNullOrEmpty(name) &&

I believe that this issue would be resolved if we replaced that line with the following:

        !String.IsNullOrEmpty(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name)) &&

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions