3

My helper in the view, which is intended to display the full name of a user who is registered in the application, and the username if logged in via 3rd party authentication.

@using MyApp.Models;

@helper GetUserName()
{
    if (User.Identity.AuthenticationType == "Application")
    {
        using (var db = new MyAppDbContext())
        {
            @db.Users.Find(User.Identity.GetUserId()).FullName
        }
    }
    else
    {
        @User.Identity.GetUserName()
    }
}

Then I use this helper:

@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-form pull-right" }))
    {
    @Html.AntiForgeryToken()

    <ul class="nav">
        <li>
            @Html.ActionLink("Hello " + GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
    }
}

The name of my user is Proba234, and it displays like this:

enter image description here

Why are those strange characters (<$G+$>) appear, and how to get rid of them?

Adam Szabo
  • 11,302
  • 18
  • 64
  • 100

2 Answers2

0

It is probably some kind of feature or bug related with usage of helpers within Visual Studio Page Inspector, you probably won't see those tags under external browser. I reproduced it easily in VS 2013. A thread about it can be found for example on ASP.NET forum

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
0

It seems like those funny characters are generated by helper. The probleem seems to be that the output of the helper is not meant to be consumed as regular string. Apparently it generates some control characters, which are meant to be there for Razor, but if we try to use the output as regular string (as @Html.ActionLink() expects its argument) they become visible.

To get rid of them, I shouldn't use the GetUserName() helper inside the @Html.ActionLink(), but get the UserName in the controller, and pass it via a property of the viewmodel. I shouldn't have that kind of logic in my view anyway.

Adam Szabo
  • 11,302
  • 18
  • 64
  • 100