How to insert css class in MvcHtmlString?

Is it possible to inject a css class into an HTML element that has been encapsulated in MvcHtmlString?

I have been instructed, as part of the structure that I am creating, to create my own versions of MVC extension methods for form elements ( TextBox, TextBoxFor<>etc.) with the following caveats:

  • that they should create the correct HTML markup, including CSS classes, in accordance with the styles that have already been developed for the site. In most cases, this simply means adding a specific class.
  • so that they are as faithful as possible to the MVC extension methods, so that developers feel comfortable with their help.

Most, if not all, of the MVC extension methods return MvcHtmlString, so the easiest way to mimic the functionality is to call these methods directly from my methods. I have my own Html Helper, OuHelperwhich my framework uses, so developers who want to create, for example TextBox, could call something in accordance with:

`@ Ou.TextBoxFor (m => m.Username)

And I would like the resulting Html to display like this:

<input type="text" name="Username" id="Username" class="int-text" />

, MVC, CSS-, , HTML-. ( TextBox 12, ). , , TagBuilder ( , , MergeAttributes), , .

: , , css, , , css. / MVC

+5
2

. / HtmlHelper, HtmlHelper , .

, , , , ASP.NET. , , , TextBoxFor, .

public static class HtmlHelperExtensions
{
    public static MvcHtmlString IntTextFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        return htmlHelper.TextBoxFor(expression, new { @class = "int-text" });
    }
}

, MVC, .

@using MyProject.Helpers;

@Html.IntTextFor(e => e.Age)
+3

@Ou.TextBoxFor(m => m.Username,new{@Class="your class Name"})

 

@Ou.TextBoxFor(m => m.Username,new{@style="font-size:10px"})
0

All Articles