【发布时间】:2017-12-12 15:25:49
【问题描述】:
如果用户是授权用户,我必须制作一个 mvc 布局视图,该视图将包含用户信息。我从视图中检查,如果用户授权然后运行 jquery 代码并将 ajax 发布到方法返回 json 的方法,我必须使用该 json 获取用户信息但是没有 jquery 我怎么能做到呢? 因为当 Index() 方法运行时,它不知道当前缓冲区是否用于授权用户。加载 Index() 后,我无法告诉控制器通过电子邮件发送我的用户信息。 如果您理解问题,请提出解决方案,如果没有,请提出问题以使我的问题更好。
我的控制器方法:
[Authorize]
[HttpPost]
public JsonResult GetUser(string email)
{
using (BlexzWebDbEntities db = new BlexzWebDbEntities())
{
var data = db.Users.Where(x => x.Email == email).FirstOrDefault();
return Json(data);
}
}
控制器代码如下:
public class DashboardController : Controller
{
// GET: Index of dashboard
[Authorize]
public ActionResult Index()
{
return View();
}
}
_Layout.cshtml代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title</title>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@{
string Name = "";
var Email = "";
if (User.Identity.IsAuthenticated)
{
Email = System.Web.HttpContext.Current.User.Identity.Name;
<script>
$.post("/Dashboard/GetUser", { email: "@Email" }).done(function (data) {
console.log(data);//here i am receiving data which i dont want to
});
</script>
}
}
</head>
<body>
</body>
</html>
下面是模型示例:
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Transections = new HashSet<Transection>();
}
public int UserId { get; set; }
public int RoleId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string PasswordHash { get; set; }
public bool IsEmailVerified { get; set; }
public string EmailVerificationToken { get; set; }
public decimal Credit { get; set; }
public string AvatarName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Transection> Transections { get; set; }
public virtual Role Role { get; set; }
}
【问题讨论】:
-
只需在布局中使用
@Html.Action()调用[ChildActionOnly]服务器方法,如果用户已通过身份验证,则返回您想要的详细信息的部分视图,如果未通过,则返回null. -
你能回答一个例子吗? @StephenMuecke
-
你想展示什么信息(
User的哪些属性)? -
我已经添加了模型给你的想法@StephenMuecke
-
假设我只想要用户身份电子邮件搜索的姓名、信用值
标签: asp.net-mvc