I've found questions on here about converting boolean values to yes/no displays, but nothing about converting Yes/No data to a boolean checkbox. We are using an ESRI geodatabase which doesn't have a boolean data type, so we have to use "Yes/No" strings for everything. That means I can't just use the normal "CheckBoxFor" HTML Helper in my editor.
I thought the solution might be to write a custom helper, but I'm kind of new to MVC and I've never done this before. Here's what I've got:
Controller:
public static class FormHelpers
{
public static IHtmlString YesNoCheckBoxFor(this HtmlHelper helper, string fieldName, string YesNoValue)
{
string htmlString = null;
if (YesNoValue == "Yes")
{
htmlString = String.Format("<input name='{0}' type='checkbox' checked='checked' value='Yes'>", fieldName);
}
else
{
htmlString = String.Format("<input name='{0}' type='checkbox' value='Yes'>", fieldName);
}
return new HtmlString(htmlString);
}
}
View:
@foreach (var field in header.Fields)
{
<div class="fieldOrderBox col-xs-12" data-fieldname="@field.Field">
<div class="col-xs-4">
@Html.YesNoCheckBoxFor("Visible", field.Visible)
</div>
<div class="col-xs-8">
<label>@Html.DisplayFor(fieldItem => field.FieldDisplay)</label>
</div>
</div>
}
The check boxes display properly and are correctly checked/unchecked. What I can't figure out is how to get the values to come back as either "Yes" or "No," and how to make a normal strongly typed helper like CheckBoxFor(field => field.Visible, ...)
using a lambda expression to indicate the field.
For context, I think I'll eventually be trying to put the values for all the "Visible" named fields into a serialized array to post to the controller via ajax (I think if you send things with the same name it puts it in an array?), but for now I'm just trying to figure out how to get "Yes" and "No" values back out, because that's something I could definitely reuse for simpler forms.