Search code examples
asp.net-mvcstringbuildermvchtmlstring

MvcHtmlString equivalent in .Net 3.5 and lower?


Is there an equivalent method to MvcHtmlString in .Net 3.5 and lower? I have googled and have not found an answer. I created a helper for MVC 3/.NET 4 that uses MvcHtmlString. However it only runs on .NET 4. I want to code a version of the helper so it can run on Mvc 2/.net 3.5 so i can use the helper on another project which uses this runtime. Would i just use stringbuilder and return Stringbuilder.ToString?


Solution

  • MvcHtmlString does work on both .NET 3.5 and .NET 4 - it has a static Create() method that should be used to create a new instance.

    The reason for the static factory method is so that runtime inspection can be used to determine if the environment is .NET 4 or .NET 3.5; if the environment is .NET 4, then a new type is declared at runtime that derives from MvcHtmlString and implements IHtmlString so that the new <%: %> response write with encoding syntax works.

    The source code for this looks like (taken from the MVC 2 Source code)

    // in .NET 4, we dynamically create a type that subclasses MvcHtmlString and implements IHtmlString
    private static MvcHtmlStringCreator GetCreator()
    {
        Type iHtmlStringType = typeof(HttpContext).Assembly.GetType("System.Web.IHtmlString");
        if (iHtmlStringType != null)
        {
            // first, create the dynamic type
            Type dynamicType = DynamicTypeGenerator.GenerateType("DynamicMvcHtmlString", typeof(MvcHtmlString), new Type[] { iHtmlStringType });
    
            // then, create the delegate to instantiate the dynamic type
            ParameterExpression valueParamExpr = Expression.Parameter(typeof(string), "value");
            NewExpression newObjExpr = Expression.New(dynamicType.GetConstructor(new Type[] { typeof(string) }), valueParamExpr);
            Expression<MvcHtmlStringCreator> lambdaExpr = Expression.Lambda<MvcHtmlStringCreator>(newObjExpr, valueParamExpr);
            return lambdaExpr.Compile();
        }
        else
        {
            // disabling 0618 allows us to call the MvcHtmlString() constructor
    #pragma warning disable 0618
            return value => new MvcHtmlString(value);
    #pragma warning restore 0618
        }
    }