繁体   English   中英

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

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

我正在使用ASP.NET MVC 5 Razor

我正在尝试将成员资格userID应用于隐藏字段,以便可以将表数据与特定用户相关联。

(用户填写存储在表中的表单,用于关联到登录配置文件的用户标识)

我只是不知道该怎么做,是我当前项目和未来项目的重要组成部分。

任何指导,建议,解决方案链接都将提供极大帮助,因为我对此一无所知。

我尝试从视图的模型类传递数据,但出现错误,提示“名称“用户”在当前上下文中不存在”

这是我的模型课的摘录

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)

由于你的模型是不是在控制器中,你需要明确地告诉代码用户对象是,它被包含在HttpContext的。 因此,请在此处更新此行:

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

到以下

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

控制器和视图基类都有对当前HttpContext的引用,这就是为什么您可以在这些项目中进行快捷方式并仅使用User.Identity 在项目的其他任何地方,您都需要完全限定的HttpContext.Current.User

编辑

在进一步查看代码时,您似乎正在尝试将用户ID保存为数据库中的列。 在这种情况下,我认为(基于您的代码示例)您应该删除最后一部分- public string UserIdentity = User.Identity.GetUserId(); 保存新的帐户信息对象时,将在其中保存用户ID。

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

扩展Brandon O'Dell的答案,在该代码块中使用“ Membership”对我不起作用(未处理的错误)。 不过,我认为他对这种解决方案的方法很棒,因为这意味着您几乎可以从任何地方调用当前用户的ID。 所以,我继续前进,玩了一点代码,瞧瞧!

如果使用“会员资格”对您也不起作用,请尝试以下一种方法:

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

这可以获取整个用户,因此,您可以在“ GeneralHelper”类(或您希望为其指定的任何名称)内创建更多方法,以获取当前用户的信息并在应用程序中使用它。

谢谢,布兰登!

为什么不只创建一个静态助手类呢?

    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