I am developing an edit form. The form i need to create needs to be dynamic so i went down the road of using EditorForModel and have many different but similar models in behind. To customize each field, i use EditorTemplates for control like dropdowns, checkboxes and radiobuttons. The project needs to be delivered soon and i have done almost everything but stuck with few things.
Here is my Sex.cshmt as EditorTemplate
@Html.RadioButton("", "M") Male
@Html.RadioButton("", "F") Female
The Edit view doesn't have much as well.
@using (Html.BeginForm("Edit", "Editor", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(m => m.Id)
@Html.EditorForModel()
<input type="submit" class="btn btn-default" value="Save" />
}
And i got a model with few properties. Very simple. Field for Sex has UIHint annotation so that it can pick up Sex editor template. And there are some Required annotation for some properties as well. These work fine.
And i got my controller action to return right type of person and return a view using a Factory. Just a standard factory with a switch statement that return right object.
public ActionResult Edit(int p)
{
var person= _service.personService.Get(p);
var canFac = new CandidateFactory(type);
var res = canFac.CreateObject(person);
return PartialView("_Edit", res);
}
In the above code, res is an dynamically created object with properties. It has a property for Sex and it's a string with value of 'M' or 'F'. I know naturally radio buttons are bools but i have to map M or F to the radio buttons.
The form was generated fine. All the normal text-boxes are populated with data. But others like Radio buttons and check-boxes aren't populated. So, my question is, In my scenario, how do i pre-populate or pre-select radio-buttons with data?
You should make use of the html attributes:
@Html.RadioButton("M","M", Model == "M" ? new { Checked = "checked" } : null) Male
@Html.RadioButton("F","F,", Model == "F" ? new { Checked = "checked" } : null) Female