How to use DataType.Custom in ASP.NET MVC 2?
Can anyone tell me how to use DataType.Custom in ASP.NET MVC 开发者_运维知识库2?
Don't use DataType.Custom
.
Instead use [DataType("YourCustomDataTypeHere")]
with an editor/display template named YourCustomDataTypeHere
.
I'd read over Brad Wilson's ASP.NET MVC 2 Template series on his blog here. It explains what you're asking better than I could.
Hope that helps.
I haven't used it personally, but looking at the MSDN it seems to just be a matter of setting DataType = DataType.Custom
and CustomDataType = "String"
. Then when you process your model you would check for DataType.Custom and if found perform different operations based on the value in CustomDataType.
Here's the sample they give on the MSDN - How to: Customize Data Field Appearance and Behavior For Non-Intrinsic Data Types in the Data Model:
public partial class TextField : System.Web.DynamicData.FieldTemplateUserControl {
string getNavUrl() {
var metadata = MetadataAttributes.OfType<DataTypeAttribute>().FirstOrDefault();
if (metadata == null)
return FieldValueString;
switch (metadata.DataType) {
case DataType.Url:
string url = FieldValueString;
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
return url;
return "http://" + FieldValueString;
case DataType.EmailAddress:
return "mailto:" + FieldValueString;
default:
throw new Exception("Unknown DataType");
}
}
protected override void OnDataBinding(EventArgs e) {
base.OnDataBinding(e);
if (string.IsNullOrEmpty(FieldValueString))
return;
var metadata = MetadataAttributes.OfType<DataTypeAttribute>().FirstOrDefault();
if (metadata == null || string.IsNullOrEmpty(FieldValueString)) {
Literal literal = new Literal();
literal.Text = FieldValueString;
Controls.Add(literal);
return;
}
if (metadata.DataType == DataType.Url ||
metadata.DataType == DataType.EmailAddress) {
HyperLink hyperlink = new HyperLink();
hyperlink.Text = FieldValueString;
hyperlink.NavigateUrl = getNavUrl();
hyperlink.Target = "_blank";
Controls.Add(hyperlink);
return;
}
if (metadata.DataType == DataType.Custom &&
string.Compare(metadata.CustomDataType, "BoldRed", true) == 0) {
Label lbl = new Label();
lbl.Text = FieldValueString;
lbl.Font.Bold = true;
lbl.ForeColor = System.Drawing.Color.Red;
Controls.Add(lbl);
}
}
}
精彩评论