RadioButtonFor not selecting value in editor templates

后端 未结 2 2117
抹茶落季
抹茶落季 2020-12-19 13:00

I have the following model:

public class Person
{
    public string Name { get; set; }
    public string Gender { get; set; }
}

I want the

相关标签:
2条回答
  • 2020-12-19 13:02

    I took this idea and expanded on it. I pass a List<Dictionary<string,string>> to my editor template as added ViewData that I use to create the radio buttons. My template looks like this

    @model string
    @{
        var buttons = (List<Dictionary<string, string>>)ViewData["Buttons"];
    }
    @foreach (var button in buttons) {
        <label class="radio inline">
            @Html.RadioButton(Html.NameForModel().ToHtmlString(), Model, Model == button["Value"], new { id = Html.IdForModel() }) @button["Label"]
        </label>
    }
    

    this is what I'm passing to my EditorFor as additional ViewData

    new { Buttons = new List<Dictionary<string, string>> { new Dictionary<string, string> { { "Label", "Commercial" }, { "Value", "Y" } }, new Dictionary<string, string> { { "Label", "Residential" }, { "Value", "N" } } } }
    

    Granted I could add this to a ViewModel type and pass that to the View from my controller, however it was quicker to do it in the cshtml file.

    0 讨论(0)
  • 2020-12-19 13:11

    I know it's ugly but the following might work:

    @model string
    @Html.RadioButton("", "F", Model == "F") Female
    @Html.RadioButton("", "M", Model == "M") Male
    

    The problem with the RadioButton helper is that if the first argument is null or empty it will always consider it as non checked thus making this helper inappropriate for editor templates.

    Here's an excerpt from the MVC source code which illustrates what I mean:

    bool isChecked = !string.IsNullOrEmpty(name) && string.Equals(htmlHelper.EvalString(name), b, StringComparison.OrdinalIgnoreCase);
    

    As an alternative you could use a custom HTML helper to generate a list of radio buttons.

    0 讨论(0)
提交回复
热议问题