Question

I have this viewmodel that has some properties and stuff that i would like to apply to the layoutpage:

public class BasicViewModel
{
    public Page Page { get; set; }
    public List<Settings> Settings { get; set; }      
}

From other threads here have i understood that this is possible but i dont really understand how.

From what I understand I somehow need to modify a controller and this is where I get confused. How do I know what controller that has to be modified and how? Any help appreciated.

Was it helpful?

Solution 2

Here goes my solution -

Lets say you have a model of this way -

public class BasicViewModel
{
    public Page Page { get; set; }
    public List<Settings> Settings { get; set; }
}

public class Page
{
    public string PageName { get; set; }
}

public class Settings
{
    public string SettingName { get; set; }
}

Then in the controller you should initiate the model in this way -

public class HomeController : Controller
{
    BasicViewModel model;
    public HomeController()
    {
        model = new BasicViewModel();
        model.Page = new Page();
        model.Settings = new List<Settings>();
    }

    public ActionResult Index()
    {
        model.Page.PageName = "My Page";
        ViewBag.LayoutModel = model;
        return View();
    }
 }

So basically we used Constructor to initiate the model and then we assign proper values in the controller action.

Then in the Layout, we can use the Model property as shown below -

<div> @ViewBag.LayoutModel.Page.PageName </div>

OTHER TIPS

In controller, Prepare an action like

public ActionResult BasicViewModelDemo
{
           BasicViewModel obj=new BasicViewModel()
           // assign properties

            return View(obj);
}

and view write some jquery. (Here i am using knockout to make view model)

<script>
   var model='@Html.Raw(Json.Encode(Model))';
   var viewmodel = ko.mapping.fromJSON(model);
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top