在asp net mvc中制作自定义助手的更好方法

时间:2011-09-05 14:38:47

标签: asp.net-mvc helper

我只是在asp net mvc 3中编写一个自定义的mvc帮助器,它可以工作..但看起来并不那么好:

public static MvcHtmlString BsCheckBox<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        string fieldName = ExpressionHelper.GetExpressionText(expression);
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);


        return MvcHtmlString.Create(
            "<input type=\"checkbox\" name=\"" + fieldName+ "_cb\" " + (metadata.Model.ToString() == "S"
                ? "checked='checked'"
                : "") + "/>" +
                  "<input type=\"hidden\" name=\"" + fieldName + "\" value=\"" + metadata.Model.ToString() + "\" />"
            );
    }

此助手创建两个输入标记元素来控制复选框。 “S”== true “N”== false

有一种更好的方法可以写同样的东西吗?

编辑:

TagBuilder看起来有点冗长:

string campo = ExpressionHelper.GetExpressionText(expression);
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

        TagBuilder element1 = new TagBuilder("input");
        element1.MergeAttribute("type","checkbox");
        element1.MergeAttribute("name", campo + "_cb");
        if (metadata.Model.ToString() == "S")
            element1.MergeAttribute("checked", "checked");

        TagBuilder element2 = new TagBuilder("input");
        element2.MergeAttribute("type", "hidden");
        element2.MergeAttribute("name", campo);
        element2.MergeAttribute("value", metadata.Model.ToString());

        return MvcHtmlString.Create(element1.ToString() + element2.ToString());

1 个答案:

答案 0 :(得分:1)