简体   繁体   中英

ASP.NET MVC placing userID in hidden field

I am using ASP.NET MVC 5 Razor

I am trying to apply the membership userID to a hidden field so that I can associate table data to a spceific user.

(users completes a form that is stored in a table, userID used to associate to login profile)

I just don't know how to do this and is an important part of my current project and future projects.

Any guidance, advice, links to solutions would be of great help as I am completely at a loss with this.

I tried passing the data from the model class for the view but I get an error saying "The name 'User' does not exist in the current context"

this is an extract of my model class

using System;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;


namespace mySite_Site.Models
{

    [Table("accountInfo")] // Table name
    public class accountInfo
    {
        [Key]
        public int AccountID { get; set; }
        public int UserIdent { get; set; } //this is the field that would store the userID for association
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Locality { get; set; }
        public string EmailAddress { get; set; }
        public bool Active { get; set; }
        public DateTime LastLoggedIn { get; set; }

        public string UserIdentity = User.Identity.GetUserId();
    }

假设您的ViewModel带有用户个人资料,则只需要类似这样的内容。

@Html.HiddenFor(m=>m.UserProfile.UserId)

Since your model is not in the controller, you need to explicitly tell the code Where the user object is, which is contained in the HttpContext. So, update this line here:

public string UserIdentity = User.Identity.GetUserId();

to the following

public string UserIdentity = HttpContext.Current.User.Identity.GetUserId();

The controller and view base classes have a reference to the current HttpContext, which is why you can shortcut in those items and simply use User.Identity . Anywhere else in your project, you will need the fully qualified HttpContext.Current.User .

Edit

In further looking at your code, it looks like you are trying to save the user Id as a column in your database. In that instance, I think (based on your code sample) that you should remove that last part - public string UserIdentity = User.Identity.GetUserId(); . When you save a new account info object, that is where you would save the user id.

var info = new accountInfo();
accountInfo.UserIdent = HttpContext.Current.User.Identity.GetUserId();
db.accountInfos.Add(info);
db.SaveChanges();

Expanding on Brandon O'Dell's answer, using "Membership" in that block of code didn't work for me (unhandled errors). Nevertheless, I think his approach to this solution is great because it means you can call the current user's Id from practically anywwhere. So, I went on ahead and played a little bit with the code, and voilá!.

In case using "Membership" doesn't work for you as well, try this one:

using <your project's name>.Models

public class GeneralHelpers
{
    public static string GetUserId()
    {
        ApplicationDbContext db = new ApplicationDbContext();
        var user = db.Users.FirstOrDefault(u => u.UserName == HttpContext.Current.User.Identity.Name);
        return user.Id;
    }
}

This one gets the whole user, so, you can create even more methods inside this "GeneralHelper" class (or whatever name you wish to give it) to get the current user's info and use it in your application.

Thanks, Brandon!

Why not just create a static helper class?

    public static class UserUtils
    {
        public static object GetUserId()
        {
            return Membership
                .GetUser(HttpContext.Current.User.Identity.Name)
                .ProviderUserKey;           
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM