Kevin himch
Kevin himch

Reputation: 297

Get user model data on view if user authorized

I have to make a mvc layout view which will have user information if user is authorized user. I am checking from view that if user authorized then run a jquery code and make ajax post to a method that method returns json and i have to use that json for user information But how can i do it without jquery? Because when Index() method is running it doesn't know if current buffer is for authorized user or not. Once Index() is loaded i can't tell controller back that send my user info by email. If you understand issue please advice solution if not then ask question to make my question better.

My Controller method:

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

Controller Code bellow:

public class DashboardController : Controller
{
    // GET: Index of dashboard
    [Authorize]
    public ActionResult Index()
    {
        return View();
    }
}

_Layout.cshtml code bellow:

<!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>

Additionally the model sample bellow:

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

Upvotes: 0

Views: 443

Answers (1)

user3559349
user3559349

Reputation:

Create a server method that returns a partial view of the User details you want to display in the Layout and render it by using the @Html.Action() method. For example

[ChileActionOnly]
public PartialViewResult UserDetails
{
    if (User.Identity.IsAuthenticated)
    {
        User model = ... // your code to get the current user
        return PartialView("_UserDetails", model);
    }
    else
    {
        return null; // assumes you do not want to display anything
    }
}

and your _UserDetails.cshtml partial

@model User
<div>@Model.FirstName</div>
.... other properties of User that you want to display

and in the Layout

@Html.Action("UserDetails", "yourControllerName");
// or @{ Html.Action("UserDetails", "yourControllerName"); }

Note if you only displaying a few properties of User, you should consider creating a view model rather than returning your data model to the view.

Upvotes: 3

Related Questions