Search code examples
razorasp.net-core-mvcviewdata

How to properly concatenate multiple variables in asp.net core ViewData[] object of a view


Up at top of my view:

@{
ViewData["Title"] = @Html.DisplayFor(model => model.SETitle);
ViewData["Description"] = @Html.DisplayFor(model => model.SEDescription);

ViewData["canonical"] = String.Concat("https://example.com/", Html.DisplayFor(model => model.CategoryURL), "/", Html.DisplayFor(model => model.URLSlug));

}

This renders in the browser like so:

<link rel="canonical" href="https://example.com/Microsoft.AspNetCore.Mvc.ViewFeatures.StringHtmlContent/Microsoft.AspNetCore.Mvc.ViewFeatures.StringHtmlContent">

I am using a standard asp.net core template. And it seems like this will always occur if you are concatenating multiple variables together for a ViewData[] string. What do I need to change about my syntax to get this actual values to pass through and render in my browser?


Solution

  • All your properties appear to be type of string so there is no need to use Html.DisplayFor() (but if you do, then it needs to be @Html.DisplayFor() - note the leading @ so the result of the method is output).

    Instead you can just use @Model.CategoryURL and @Model.URLSlug.

    And if https://example.com/ is your site, then you should be doing this using the Url.Action() method to generate the correct relative url without hard-coding the site name.

    In addition, you have commented that these values are being used in your layout, in which case, consider using base view model containing those properties and set them in the controller method so that the Layout uses @model yourBaseViewModel, and each view that uses that layout inherits from your base view model