How to create a common view model in MVC?

I would like to use viewmodel in MVC instead of using viewbag. Is there a way to create some general view model that will be shared among all my controllers and then use this in my views? What code do I need for this? I thought I could create something in the base controller. Is it possible?

+5
source share
1 answer

I believe that the predominant method of transferring data between controllers and views is to create a class that represents the data that you want to pass to your view and pass this model variable to the view method.

/Models/Home/IndexViewModel.cs

namespace MyProject.Models.Home
{
  public class IndexViewModel
  {
    public string Message { get; set; }
  }
}

Controllers /HomeController.cs

public class HomeController
{
  public ActionResult Index()
  {
    IndexViewModel model = new IndexViewModel();
    model.Message = "Hello World!";
    View(model);
  }
}

/Views/Home/Index.cshtml ( Razor MVC3)

@Model MyProject.Models.Home.IndexViewModel //strongly-typed view

<h1>@model.Message</h1>

. MyClass. , , . , , ( ).

, , :

/Models/SharedData.cs

namespace MyProject.Models
{
  public class SharedData
  {
    public DateTime Birthday { get; set; }
  }
}

, SharedData.

/Models/ISharedDataViewModel.cs

namespace MyProject.Models
{
  public interface ISharedDataViewModel
  {
    public SharedData Data { get; set; }
  }
}

Home IndexViewModel, shareddata​​p >

/Models/Home/IndexViewModel.cshtml

namespace MyProject.Models.Home
{
  public class IndexViewModel: ISharedDataViweModel
  {
    public string Message { get; set; }
    public ShardedData Data { get; set; }
  }
}

, ,

/Views/Shared/SharedDataView.cs ( Razor MVC3)

@Model MyProject.Models.ISharedDataViewModel //strongly-typed partial view

@if (model != null && model.Data != null)
{
<h3>@model.Data.Birthday.ToString()</h3>
}

,

/Views/Home/Index.cshtml ( Razor MVC3)

@Model MyProject.Models.Home.IndexViewModel //strongly-typed view

<h1>@model.Message</h1>

@Html.Partial("SharedDataView", model) 

, ISharedDataViewModel.

+7

All Articles