简体   繁体   English

ASP.NET MVC在隐藏字段中放置用户ID

[英]ASP.NET MVC placing userID in hidden field

I am using ASP.NET MVC 5 Razor 我正在使用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. 我正在尝试将成员资格userID应用于隐藏字段,以便可以将表数据与特定用户相关联。

(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. 由于你的模型是不是在控制器中,你需要明确地告诉代码用户对象是,它被包含在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 . 控制器和视图基类都有对当前HttpContext的引用,这就是为什么您可以在这些项目中进行快捷方式并仅使用User.Identity Anywhere else in your project, you will need the fully qualified HttpContext.Current.User . 在项目的其他任何地方,您都需要完全限定的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. 在进一步查看代码时,您似乎正在尝试将用户ID保存为数据库中的列。 In that instance, I think (based on your code sample) that you should remove that last part - public string UserIdentity = User.Identity.GetUserId(); 在这种情况下,我认为(基于您的代码示例)您应该删除最后一部分- public string UserIdentity = User.Identity.GetUserId(); . When you save a new account info object, that is where you would save the user id. 保存新的帐户信息对象时,将在其中保存用户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). 扩展Brandon O'Dell的答案,在该代码块中使用“ Membership”对我不起作用(未处理的错误)。 Nevertheless, I think his approach to this solution is great because it means you can call the current user's Id from practically anywwhere. 不过,我认为他对这种解决方案的方法很棒,因为这意味着您几乎可以从任何地方调用当前用户的ID。 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. 这可以获取整个用户,因此,您可以在“ GeneralHelper”类(或您希望为其指定的任何名称)内创建更多方法,以获取当前用户的信息并在应用程序中使用它。

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;           
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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