2014-01-08 59 views
0

我使用ASP.NET MVC 5剃刀ASP.NET MVC將用戶ID的隱藏字段

我試圖會員用戶ID應用到隱藏字段,這樣我可以給spceific用戶表中的數據相關聯。

(用戶完成存儲在一個表中的形式,用戶ID用於關聯到登錄配置文件)

我只是不知道如何做到這一點,是我當前的項目和未來項目的重要組成部分。

任何指導,建議,解決方案的鏈接都會有很大幫助,因爲我完全不知所措。

我試圖從模型類傳遞數據的看法,但我得到一個錯誤說「這個名字‘用戶’不會在目前情況下存在」

這是我的模型類的提取物

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

回答

1

擴大布蘭登·奧德爾的回答,使用「會員制」的代碼塊,我(未處理的錯誤),沒有工作。儘管如此,我認爲他對這個解決方案的態度非常好,因爲這意味着您可以從任何地方調用當前用戶的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」更加方法類(或任何你想給它的名字)來獲取當前用戶的信息並在你的應用程序中使用它。

謝謝布蘭登!

2

你只需要像這樣的東西,假設你的ViewModel上有用戶配置文件。

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

我在我的模型中試過這個 - public string UserIdentity = User.Identity.GetUserId();但得到以下錯誤「名稱用戶在當前上下文中不存在」 – user2029541

+0

@ user2029541聽起來像你的問題根本不是關於隱藏的字段。 – MikeSmithDev

+0

請您詳細說明一下Mike Mike – user2029541

1

爲什麼不只是創建一個靜態輔助類?

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

由於你的模型是不是在控制器中,你需要明確地告訴代碼用戶對象是,它被包含在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(); 
+0

湯米謝謝,現在它更有意義,我沒有這樣想,更直接地保存信息而不是首先將它傳遞給表單。 – user2029541