0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.