Search code examples
asp.netasp.net-mvcasp.net-mvc-5user-accountsuser-management

Accessing info from database asp.net mvc 5


I have added as below to get some more user info, and updated the database, it all works as it should, however im trying to add in the index view of manage folder so that the FullName, birthdate and Country will show, but i cant really get it working... can someone point me in the right direction?

AccountController:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, FullName = model.FullName, Country = model.Country, BirthDate = model.BirthDate };
        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);
}

accountviewmodel:

public class RegisterViewModel
{
    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Full Name")]
    public string FullName { get; set; }

    [Required]
    public DateTime BirthDate { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Country")]
    public string Country { get; set; }
}

IdentityModels:

public class ApplicationUser : IdentityUser
{
    public string FullName { get; set; }
    public string Country { get; set; }
    public DateTime BirthDate { get; set; }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

Index.cshtml

<div>
<h4>Change your account settings</h4>
<hr />
<dl class="dl-horizontal">
    <dt>Full Name:</dt>
    <dd></dd>

    <dt>Birth Date:</dt>
    <dd></dd>

    <dt>Country:</dt>
    <dd>
        Comming soon
    </dd>


    <dt>Password:</dt>
    <dd>
        [
        @if (Model.HasPassword)
        {
            @Html.ActionLink("Change your password", "ChangePassword")
        }
        else
        {
            @Html.ActionLink("Create", "SetPassword")
        }
        ]
        </dd>

AccountViewModels:

public class SetNameViewModel
{
    [Display(Name ="Set Name")]
    public string SetName { get; set; }
}

public class SetCountryViewModel
{
    [Display(Name = "Set Country")]
    public string SetCountry { get; set; }
}

ManageController:

   public async Task<ActionResult> Index(ManageMessageId? message)
    {
        ViewBag.StatusMessage =
            message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
            : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
            : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
            : message == ManageMessageId.Error ? "An error has occurred."
            : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
            : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
            : "";

        var userId = User.Identity.GetUserId();
         //ADDED THEESE LINES
     var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
           var currentUser = manager.FindById(User.Identity.GetUserId());
      ////
        var model = new IndexViewModel
        {
            HasPassword = HasPassword(),
            PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
            TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
            Logins = await UserManager.GetLoginsAsync(userId),
            BrowserRemembered = await        AuthenticationManager.TwoFactorBrowserRememberedAsync(userId),

        };
        return View(model);
    }

Now if i use:

    @User.Identity.GetUserId()

in my view i get the user id, but how do i fetch fullname etc?

  @User.Identity.GetUserName()

returns me the username of the id aswell

added

         ViewBag.CurrentUser = currentUser;

to my managecontroller and now i can get the things i want in view with @Viewbag.CurrentUser.Country, BirthDate and Fullname! yay me, now i want to give the users the option to edit their info... that will be a harder cookie to crumble i guess!


Solution

  • Adding ViewBag.CurrentUser = currentUser; to the ManageController worked out for me!