Search code examples
asp.net-mvcvalidationmodelsviewdata

ASP.NET MVC: Passing several objects to the view including a validation model


I like using Models for validation

<!-- ViewPage -->

<%@ Page Language="C#" Inherits="ViewPage<TopicModel>" %>

...

<%= Html.TextBoxFor(m => m.Title) %>

...

<%= Html.TextBoxFor(m => m.Description) %>


// Controller

[HttpPost]
public ActionResult NewTopic(TopicModel model)
{
     // validate
}

It works great, but when I need to pass additional data, I need to create a new ViewModel class and I loose the flexibility.

<!-- ViewPage -->

<%@ Page Language="C#" Inherits="ViewPage<TopicViewModel>" %>

<%= Model.SomethingImportant %>

...

<%= Html.TextBoxFor(m => m.TopicModel.Title) %> // UGLY, I get name="TopicViewModel.TopicModel.Title"

...

<%= Html.TextBoxFor(m => m.TopicModel.Description) %> // UGLY, same thing


// Controller

[HttpPost]
public ActionResult NewTopic(TopicViewModel model)
{
     // validate
     var validationModel = model.TopicModel; // UGLY
}

How can I make it easier and better looking?


Solution

  • Have you considered using the ViewData dictionary for your additional data outside of the model?

    Update Alternatively, make your view model a subclass of your model and add the extra properties, but retain the validation of the base class.