4

For each entity in my repository, I have a view model and an input model. I find having an input model to store relational IDs (as opposed to foreign entities) makes rendering select lists easier, but which model do you pass to your Edit view for rendering, View Model or Input Model?

Sample POST action for Category entity:

[HttpPost]
public ActionResult Edit(CategoryInputModel inputModel)
{
    // map inputModel to entity and persist
    // ...
}

View Model:

[HttpGet]
public ActionResult Edit(int id)
{
    var category = _unitOfWork.CurrentSession.Get<Category>(id);
    var viewModel = Mapper.Map<Category, CategoryViewModel>(category);
    return View(viewModel);
}

In this case the edit view form would take care of providing the correct input model fields for the POST action.

Input Model:

[HttpGet]
public ActionResult Edit(int id)
{
    var category = _unitOfWork.CurrentSession.Get<Category>(id);
    var inputModel = Mapper.Map<Category, CategoryInputModel>(category);
    return View(inputModel);
}

Which is easier to maintain in the long run?

1
  • can you add your View and Input Model code? I don't know but in my experience I've always seen using the same Model for both purposes.
    – neebz
    Apr 21, 2011 at 14:49

2 Answers 2

3

I'm now using an input model that does not contain an ID. I keep the entity ID as the action parameter, like so:

[HttpPost]
public ActionResult Edit(Guid id, CategoryInputModel inputModel)
{
    var category = _categoryRepository.Get(id);
    // do mappings from inputModel to category and save
    // ...
}
2

I use the same ViewModel when the detail/edit screens are exactly the same.

But like you've noticed, when the screens are different I do use a InputModel, I call them FormModels.

I consider ViewModels really cheap to maintain with AutoMapper. Using .AssertConfigurationIsValid() ( I forget the exact method name ) tells you right away what went out of synch between domain/buisness objects and Form/View Models.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.