我在表格中存储了这样的用户信息:
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);
}
请帮助您采用适当的方法 谢谢。
答案 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);
}