使用FluentHtml(MVCContrib)创建自定义输入元素时出现问题

时间:2010-01-27 06:09:46

标签: asp.net-mvc mvccontrib fluenthtml

我刚刚开始涉足ASP.NET MVC 1.0并遇到了精彩的MVCContrib。我最初走的是创建一些扩展的html帮助器的路径,但在找到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>元素中。

我在这里缺少什么?

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

一切正常......

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));
    }
}
相关问题