Converting objects in my MVC3 View
A user can upload a new document and add information, every document has a set of default properties. The admin has the ability to add a small amount of extra properties. He can add a string, bool, datetime value.
When generating my View I get a Dictionary<String,Object>
with the extra 开发者_运维知识库properties.
In my view I want to generate the right control for the object. So when it's a datetime object I want to load the jquery calendar, boolean a checkbox etc.
@switch (Model.ExtraFields[i].PropertyType)
{
case (short)Enums.PropertyType.Boolean:
@Html.TextBoxFor(model => Convert.ToBoolean(Model.Values[i].ExtraFieldValue))
break;
case (short)Enums.PropertyType.DateTime:
@Html.TextBoxFor(model => Convert.ToDateTime(Model.Values[i].ExtraFieldValue))
break;
default:
@Html.TextBoxFor(model => Model.Values[i].ExtraFieldValue)
break;
}
It always gives an error on the Convert.To...
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Any idea's?
The EditorFor
, TextBoxFor
and so on all require an expression which gives them access to meta data on the property that you're using. Convert.ToDateTime
removes that access (because it returns a value instead) so the methods don't know what property name to use or any additional information like a [Display]
attribute. I would suggest you do something like:
@switch (Model.ExtraFields[i].PropertyType) {
case (short)Enums.PropertyType.Boolean:
@Html.EditorFor(model => Model.Values[i].ExtraFieldValue, "BooleanEditor")
break;
case (short)Enums.PropertyType.DateTime:
@Html.EditorFor(model => Model.Values[i].ExtraFieldValue, "DateTimeEditor")
break;
default:
@Html.TextBoxFor(model => Model.Values[i].ExtraFieldValue)
break;
}
Then you create EditorTemplates
(as a subdirectory of your controller with specific templates named BooleanEditor.cshtml
and so forth like so:
@model object
@Html.CheckBox("", Convert.ToBoolean(Model))
by leaving the first parameter blank you're going to automatically use the property name supplied via the expression from the call to EditorFor
.
精彩评论