RadioButton To select a value in editor templates

I have the following model:

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

I want the default gender to be female, so I set this in action:

public ActionResult Create()
{
    var model = new Person { Gender = "F" }; // default is female
    return View(model);
}

Finally, the view displays everything like this:

@model Person

@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <p><input type="submit" value="Create" /></p>
}

Everything works as expected. Now let's say that instead of a simple text field, I want to show the floor as a more intuitive pair of radio buttons. So I make the following template and save it in Shared / EditorTemplates / Gender.cshtml:

@model string
@Html.RadioButtonFor(model => model, "F") Female
@Html.RadioButtonFor(model => model, "M") Male

Finally, I decorate the floor [UIHint("Gender")].

Paul is now correctly displayed using the switches, which is great, BUT ...

Problem

A woman is no longer selected as the default, and instead I end up with two radio consoles. Did I miss something?

, RadioButtonFor ( model => model model => model.Gender), , . , , - , , , .

+5
2

, , :

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

RadioButton , , , .

MVC, , :

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

HTML- .

+9

. List<Dictionary<string,string>> , ViewData, .

@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>
}

, EditorFor ViewData

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

, ViewModel , cshtml.

0

All Articles