开发者

How would I pass viewmodel class to repository class

I have created a viewmodel class for my custom view template. Right now I am calling the database save method in Controller class. Now I would like to move this logic to the Repository class. How can I access my viewModel properities in my repository class? I appreciate any input. Thank you.

Here is my 开发者_开发问答code.

ViewModel

    public SelectList StatusList { get; set; }
    [Required(ErrorMessage = "* Required")]
    public string Status { get; set; }

    [Required]
    public DateTime? StartDate { get; set; }

My Contoller class:

[HttpPost]
    public ActionResult Create(CreateViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            // go and save your view model data  
            using (var adapter = new DataAccessAdapter())
            {
                    TestEntity test1 = new TestEntity();
                    test1.statusId = Convert.ToInt32(viewModel.Status);
                    adapter.SaveEntity(test1);

                    TestEntity1 test2 = new TestEntity2();
                    test2.mId = test1.mId;
                    test2.startDate = viewModel.startDate;
                    adapter.SaveEntity(test2);
           }
        }

}


You don't want to access your view model properties in your repository, you want to map the view model properties back onto your entity class and pass the entity to your repository. The entity should be in a library known to both the MVC application and your data library.

public class TestController
{
  public ITestRepository _repository;

  public TestController(ITestRepository repository)
  {
    _repository = repository;
  }

  public ActionResult Create(CreateViewModel viewModel)
  {
    var entity = new TestEntity()
      { statusId = Int32.Parse(viewModel.Status) };
    var entity2 = new TestEntity2()
      { mId = entity.mId,
        startDate = viewModel.startDate };

    _repository.SaveEntity(entity);
    _repository.SaveEntity2(entity2);
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜