我最近刚刚开始涉足ASP.NET MVC1.0,偶然发现了非常棒的MVCContrib。我原本打算创建一些扩展的html helper,但在找到FluentHTML之后,我决定尝试创建一个自定义的输入元素。因此,简而言之,我想用额外的标记包装某些输入元素。例如,可以将TextBox包装在<li />中。
我根据Tim Scott在另一个问题中的回答创建了我的自定义输入元素:DRY in the MVC View。
因此,为了进一步详细说明,我创建了我的类"TextBoxListItem":
public class TextBoxListItem : TextInput<TextBox>
{
public TextBoxListItem (string name) : base(HtmlInputType.Text, name) { }
public TextBoxListItem (string name, MemberExpression forMember, IEnumerable<IBehaviorMarker> behaviors) : base(HtmlInputType.Text, name, forMember, behaviors) { }
public override string ToString()
{
var liBuilder = new TagBuilder(HtmlTag.ListItem);
liBuilder.InnerHtml = ToString();
return liBuilder.ToString(TagRenderMode.SelfClosing);
}
}我还将其添加到我的ViewModelContainerExtensions类中:
public static TextBox TextBoxListItem<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class
{
return new TextBoxListItem(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors)
.Value(expression.GetValueFrom(view.ViewModel));
}最后,我也将它添加到了ViewDataContainerExtensions中:
public static TextBox TextBoxListItem(this IViewDataContainer view, string name)
{
return new TextBox(name).Value(view.ViewData.Eval(name));
}在我的视图中,我这样命名它:
<%= this.TextBoxListItem("username").Label("Username:") %>无论如何,除了标准的FluentHTML TextBox之外,我没有得到任何其他东西,没有包装在<li></li>元素中。
这里我漏掉了什么?
非常感谢你的帮助。
发布于 2010-05-08 15:11:09
一切都正常..。
public class TextBoxListItem : TextInput<TextBoxListItem>
{
public TextBoxListItem(string name) : base(HtmlInputType.Text, name) { }
public TextBoxListItem(string name, MemberExpression forMember, IEnumerable<IBehaviorMarker> behaviors) : base(HtmlInputType.Text, name, forMember, behaviors) { }
public override string ToString()
{
var liBuilder = new TagBuilder(HtmlTag.ListItem);
liBuilder.InnerHtml = base.ToString();
return liBuilder.ToString(TagRenderMode.Normal);
}
}
public static class ViewDataContainerExtensions
{
public static TextBoxListItem TextBoxListItem(this IViewDataContainer view, string name)
{
return new TextBoxListItem(name).Value(view.ViewData.Eval(name));
}
}
public static class ViewModelContainerExtensions
{
public static TextBoxListItem TextBoxListItem<T>(this IViewModelContainer<T> view, Expression<Func<T, object>> expression) where T : class
{
return new TextBoxListItem(expression.GetNameFor(view), expression.GetMemberExpression(), view.Behaviors)
.Value(expression.GetValueFrom(view.ViewModel));
}
}https://stackoverflow.com/questions/2144906
复制相似问题