capiono
capiono

Reputation: 2997

Passing objects to layout in mvc 5

I'm passing objects to the Layout from the controller like this:

public ActionResult MyProfile()
{
  var roles = new List<int?>();
  User.Roles.ForEach(r => roles.Add(r.ID));
  return View(new ProfileModel()
  {
    LoginUser = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string.IsNullOrEmpty(User.LastName) ? string.Empty : User.LastName.ToLower()),
    UserRole = new List<int?>(roles)
  });
}

public class ModelBase {

    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string LoginUser { get; set; }

    public List<int?> UserRole { get; set; }

    public ModelBase() {
        UserRole = new List<int?>();
    }
}

 public class ProfileModel : ModelBase { }

This works but, I have to do this for all my Controller Action when returning a view because I need the roles and login user on all my views.

Is there a way for me to do this just once, without having to repeat it in my actions?

I try adding to it to a base controller, but ROLES and LOGINUSER were always null.

I know this has been addressed a lot on SO, but they are all doing the something.

Thanks.

Upvotes: 0

Views: 275

Answers (3)

capiono
capiono

Reputation: 2997

Using Stephen Muecke suggestion I did this:

 [ChildActionOnly]
    public PartialViewResult Navigation() {
        return PartialView("_Navigation", new LayoutModel(User));
    }

    [ChildActionOnly]
    public PartialViewResult LoginInfo() {
        return PartialView("_LoginInfo", new LoginInfoModel(User));
    }

And

<div class="collapse navbar-collapse" id="navbar-collapse-area">
        @Html.Action("LoginInfo", "Home")
</div>

 <div class="col-lg-2 sidebox">
        <div class="sidebar content-box" style="display: block;">
            @Html.Action("Navigation", "Home")
        </div>
 </div>

Bernard's suggestion also works, but i prefer this.

Upvotes: 3

alisabzevari
alisabzevari

Reputation: 8126

I think it is not a bad practice to write some code in your layout. If it is a razor view or something similar you can add user name and its roles directly in the view.

Upvotes: 0

Bernard Moes
Bernard Moes

Reputation: 51

Try this:

public ActionResult MyProfile()
{
    var roles = new List<int?>();
    User.Roles.ForEach(r => roles.Add(r.ID));
    return View(new ProfileModel(User));
}

Model:

public class ModelBase 
{
    public ModelBase(User user) {
        UserRole = new List<int?>();
        LoginUser =  CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string.IsNullOrEmpty(user.LastName) ? string.Empty : user.LastName.ToLower()),
    }

    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string LoginUser { get; set; }

    public List<int?> UserRole { get; set; }
}

ProfileModel:

public class ProfileModel : ModelBase 
{ 
    public ProfileModel(User user) : base(user) { }
}

Upvotes: 1

Related Questions