skip to Main Content

I have a asp.net core mvc project.

In my layout file, I want to display the name of the currently logged in user, such that the username is displayed in the header. For this, I want to be able to call a function in my homecontroller that does this.
So, I made a simple function taht looks like this in the home controller:

    public String GetLoggedInuser()
    {
        return "garse garsebro";
    }

And then I have tried every method I have been able to find. The first couple of methods here are just function suggested around the web, that are simply not available to me:

@HtmlHelper.Action("GetLoggedInuser");
@Html.RenderAction("GetLoggedInuser");

To name a few. Then there is this one, which I can find:

 @Html.ActionLink("GetLoggedInuser")

But for this one, my function "GetLoggedInuser" can’t be found anywhere.

How do you, in a razor page call a controller function that you can get returned a string from that function and display it?

2

Answers


  1. If you are using Microsoft.AspNet.Identity then below line will do the work post login.

    @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
    
    Login or Signup to reply.
  2. You can try to use ajax to call action to get the username,and add it to html:

    <div id="username">
    
    </div>
    @section scripts
    {
    
        <script>
            $(function () {
                $.ajax({
                    type: "GET",
                    url: 'GetLoggedInuser',
                }).done(function (result) {
                    $("#username").html(result);
                });
            })
        </script>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search