登录用户(当前用户)的信息

时间:2016-02-23 12:28:48

标签: asp.net-mvc asp.net-mvc-5

我在表格中存储了这样的用户信息:

ID(PK) |  Email     | Pass | DepartmentID
 1      abc@g.com    hash    301
 2      abcd@g.com   hash    302
 3      abcd@g.com   hash    303

现在,我需要从视图端通过jQuery getJson调用获取当前用户(登录用户的)部门ID,但找不到任何合适的方法。

视图中的我的脚本(片段)类似于:

   var url="@Url.Action("Details","Users")";
    $.getJSON(url, function(data){

       $("#DeptID").val(data.DepartmentID);

});

我在控制器(代码段)中的代码是:

public ActionResult Details()
{
    var user = User.Identity.Name;
    return Json(user, JsonRequestBehavior.AllowGet);
}

请帮助您采用适当的方法 谢谢。

1 个答案:

答案 0 :(得分:3)

假设您的派生ApplicationUser/IdentityUser具有您在原始帖子中描述的属性

public async Task<ActionResult> Details(){
    var username = User.Identity.Name;
    //retrieve user based on some identifier.
    var user = await userManager.FindByNameAsync(username);
    object result = new object();
    if (user != null) {
        //construct a result with the data you want to send to the client.
        result = new {
            Email = user.Email,
            DepartmentID = user.DepartmentID,
        }
    }

    return Json(result, JsonRequestBehavior.AllowGet);
}