开发者

Better way to make a custom helper in asp net mvc

开发者 https://www.devze.com 2023-04-02 07:22 出处:网络
I just write a custom mvc helper in asp net mvc 3 and it works.. but it does not look that good: public static MvcHtmlString BsCheckBox<TModel, TValue>(this HtmlHelper<TModel> html, Expre

I just write a custom mvc helper in asp net mvc 3 and it works.. but it does not look that good:

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() + "\" />"
            );
    }

This helper creates t开发者_开发知识库wo input tag elements to control the checkbox. "S" == true "N" == false

There is a better way to write the same thing?

Editing:

The TagBuilder looks a little verbose:

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());


Use TagBuilder: http://www.asp.net/mvc/tutorials/using-the-tagbuilder-class-to-build-html-helpers-cs

0

精彩评论

暂无评论...
验证码 换一张
取 消