Displaying welcome message on navbar!

1

I'm doing an application in MVC asp.net . When the user logs in, I would like them to display the welcome message with the user name, however you are bringing the email, how do I change it?

My action looks like this:

@Html.ActionLink("Olá " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
    
asked by anonymous 23.01.2018 / 19:34

1 answer

4
If you are using the ASP.NET MVC template with Identity , by default it already saves the Username with the email entered in the Register method, see:

[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
            return RedirectToAction("Index", "Home");
        }
            AddErrors(result);
    }
        return View(model);
}

You can change this behavior ... How?

Change your class RegisterViewModel :

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required,Display(Name = "Username")]
    public string Username { get; set; }


    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }  
}

And in View Register.cshtml add the field that will receive Username

<div class="form-group">
        @Html.LabelFor(m => m.Username, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
        </div>
    </div>

Once this is done, change what Username is getting in method Register to AccountController

var user = new ApplicationUser { UserName = model.Username, Email = model.Email };

And then, your Username will have the value informed, at the time of registration. =)

    
24.01.2018 / 00:45