62,046
社区成员
发帖
与我相关
我的任务
分享
public class TestModel
{
[Required]
public Guid MyId { get; set; }
[Required]
public LedSizeModel LedSize { get; set; }
}
public class LedSizeModel
{
public int Left { get; set; }
public int Top { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
@Html.EditorFor(model => model.LedSize, new { htmlAttributes = new { @class = "form-control" } })
public static MvcHtmlString EditorLedSizeFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelpr, Expression<Func<TModel, TValue>> expression,
object htmlAttributes)
{
var tmp = ModelMetadata.FromLambdaExpression(expression, htmlHelpr.ViewData);
if (tmp.ModelType != typeof(LedSizeModel))
{
throw new InvalidCastException(string.Format("不能将{0}转换为{1}", tmp.ModelType.ToString(), typeof(LedSizeModel).ToString()));
}
string modelName = ExpressionHelper.GetExpressionText(expression);
TagBuilder tagBuilder = new TagBuilder("input");
tagBuilder.Attributes.Add("type", "text");
tagBuilder.Attributes.Add("name", modelName);
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (attributes.ContainsKey("htmlAttributes"))
{
var attr = HtmlHelper.AnonymousObjectToHtmlAttributes(attributes["htmlAttributes"]);
if (attr.ContainsKey("class"))
{
attr["class"] = "text-box single-line " + attr["class"];
}
else
{
attr.Add("class", "text-box single-line");
}
tagBuilder.MergeAttributes(attr, false);
}
LedSizeModel tmpModel = (LedSizeModel)tmp.Model;
tagBuilder.Attributes.Add("value", string.Format("{0},{1},{2},{3}", tmpModel.Left, tmpModel.Top, tmpModel.Width, tmpModel.Height));
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));
}
然后在View里如下调用就可以了:
@Html.EditorLedSizeFor(model => model.LedSize, new { htmlAttributes = new { @class = "form-control" } })
当然,还有一些后续的工作,例如客户端验证输入等,实现 ValidationAttribute 这个特性,就可以自定义模型验证了。