The '+' operator cannot be applied to operands of type MvcHtmlString

I convert an ASP.NET MVC application to ASP.NET MVC 2 4.0 and get this error:

The + operator cannot be applied to operands of the type System.Web.Mvc.MvcHtmlString and System.Web.Mvc.MvcHtmlString

HTML = Html.InputExtensions.TextBox(helper, name, value, htmlAttributes) + Html.ValidationExtensions.ValidationMessage(helper, name, "*"); 

How can this be fixed?

+6
c # asp.net-mvc-2
source share
6 answers

You cannot combine instances of MvcHtmlString . You need to either convert them to regular strings (via .ToString() ), or do it differently.

You can also write an extension method, see this answer for an example: How to concatenate multiple instances of MvcHtmlString

+5
source share

Personally, I use a very subtle utility method that uses the existing Concat () method in the string class:

 public static MvcHtmlString Concat(params object[] args) { return new MvcHtmlString(string.Concat(args)); } 
+4
source share

The @Anders method as an extension method. The best part is that you can add several MvcHtmlStrings along with other values ​​(for example, regular strings, ints, etc.), since ToString is called on each object automatically by the system.

  /// <summary> /// Concatenates MvcHtmlStrings together /// </summary> public static MvcHtmlString Append(this MvcHtmlString first, params object[] args) { return new MvcHtmlString(string.Concat(args)); } 

Call example:

 MvcHtmlString result = new MvcHtmlString(""); MvcHtmlString div = new MvcHtmlString("<div>"); MvcHtmlString closediv = new MvcHtmlString("</div>"); result = result.Append(div, "bob the fish", closediv); result = result.Append(div, "bob the fish", closediv); 

It would be much better if we could overload operator +

+1
source share

Here is my way:

  // MvcTools.ExtensionMethods.MvcHtmlStringExtensions.Concat public static MvcHtmlString Concat(params MvcHtmlString[] strings) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (MvcHtmlString thisMvcHtmlString in strings) { if (thisMvcHtmlString != null) sb.Append(thisMvcHtmlString.ToString()); } // Next thisMvcHtmlString MvcHtmlString res = MvcHtmlString.Create(sb.ToString()); sb.Clear(); sb = null; return res; } // End Function Concat 
0
source share
  public static MvcHtmlString Concat(params MvcHtmlString[] value) { StringBuilder sb = new StringBuilder(); foreach (MvcHtmlString v in value) if (v != null) sb.Append(v.ToString()); return MvcHtmlString.Create(sb.ToString()); } 
0
source share

Refusing the @mike nelson example, this was the best solution for me:

No additional helper methods are needed. In your razor file do something like:

 @foreach (var item in Model) { MvcHtmlString num = new MvcHtmlString(item.Number + "-" + item.SubNumber); <p>@num</p> } 
0
source share

All Articles