Operator '+' cannot be applied to operands of type MvcHtmlString
I am c开发者_如何学Goonverting an ASP.NET MVC application to ASP.NET MVC 2 4.0, and get this error:
Operator '+' cannot be applied to operands of 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 remedied?
You can't concatenate instances of MvcHtmlString
. You will either need to convert them to normal strings (via .ToString()
) or do it another way.
You could write an extension method as well, see this answer for an example: How to concatenate several MvcHtmlString instances
Personally I use a very slim utility method, that takes advantage of the existing Concat() method in the string class:
public static MvcHtmlString Concat(params object[] args)
{
return new MvcHtmlString(string.Concat(args));
}
@Anders method as an extension method. The nice thing about this is you can append several MvcHtmlStrings together along with other values (eg normal strings, ints etc) as 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));
}
Example call:
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 nicer if we could overload operator+
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
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());
}
Working off of @mike nelson's example this was the solution that worked best for me:
No need for extra helper methods. Within your razor file do something like:
@foreach (var item in Model)
{
MvcHtmlString num = new MvcHtmlString(item.Number + "-" + item.SubNumber);
<p>@num</p>
}
精彩评论