Search code examples
c#asp.net-mvcasp.net-core-mvcnullreferenceexception

MvcHtmlString in ASP.NET Core 6 MVC


I am migrating an application from ASP.NET MVC 5 running on .NET 4.8 to ASP.NET Core 6 MVC.

The MVC 5 application has the following:

 public static MvcHtmlString BuildColoredIconTag(string iconName, string color)
 {
    var icon = BuildInternalColoredIconTag(iconName, color);

    var htmlBuilder = new StringBuilder();

    htmlBuilder.Append(icon);

    var finalHtml = icon.ToString(TagRenderMode.Normal);

    return MvcHtmlString.Create(finalHtml);
}

I updated it to the following in the new application:

public static HtmlString BuildColoredIconTag(string iconName, string color)
{
    var icon = BuildInternalColoredIconTag(iconName, color);

    var htmlBuilder = new StringBuilder();

    htmlBuilder.Append(icon);

    var finalHtml = icon.TagRenderMode.ToString();

    return new HtmlString(finalHtml);
}

Is this correct or should I update it to something else? I cannot test it yet because I am adding other components.

I have the following in a partial .cshtml file, but I receive null reference warnings:

@IconExtensions.BuildColoredIconTag(ViewData["icon"].ToString(), "text-info")

What should I update it to?


Solution

  • It was caused by this line in your csproj file

    <Nullable>enable</Nullable>
    

    as mentioned in the document:

    By default, nullable annotation and warning contexts are disabled. That means that your existing code compiles without changes and without generating any new warnings. Beginning with .NET 6, new projects include the enable element in all project templates.

    If you don't like it ,just disable it

    <Nullable>disable</Nullable>
    

    If you want to keep it without warning ,declearing iconName as string? or trying with ?? operater

    like:

    ViewData["icon"]?.ToString()??"DefaultIcon"