haddow64 haddow64 - 1 year ago 66
ASP.NET (C#) Question

Pass class instance to all views

I have an Asp.Net MVC application using domain authentication, the _Layout.cshtml file contains a call to

which on the domain environment returns the correct domain username.

I have a
model that stores that individuals details.

In the Home Controller I instance the class and pass it into my view:

public ActionResult Index()
var personInstance = new Person((User.Identity.Name));
return View(personInstance);

Then in my _Layout.cshtml I add the model I'm using:

@model namespace.Models.Person

Then from there I replace
with the required property

<p class="nav navbar-text navbar-right">Hello, @Model.fullName</p>
@*<p class="nav navbar-text navbar-right">Hello, @User.Identity.Name</p>*@

This works fine for the Home Views but if I access another view that is already using another model it throws an exception:

The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[namespace.Models.Logging]', but
this dictionary requires a model item of type

What is the best way to tackle this?

Answer Source

You need to extend the View Model to expose a Person property and then create an instance of this, populating it in a similar manner and pass it into your view.

var model = new MyModel();
model.Person = new Person((User.Identity.Name));
return View(model);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download