ASP.NET MVC – What is a ViewModel?

A ViewModel could be simplified as the data that we pass to the view.

So, that data could have many objects (other classes) or simple entities.

We can apply some validation rules to that data, using Data annotations.

Or we can simply show what we want on the view.

Let’s make an example.

We are creating a website about Robot dogs. Everybody has one of this in his plans.

public class RobotDog
{
    public string Name { get; set; }

    public int Age { get; set; }

    public DateTime DateCreation { get; set; }
}

Now we would like to show a page for creating these robot dogs.
We will set the DateCreation property and we would like to add some validation rule.

So we create a view model!

public class RobotDogCreationViewModel
{
    [Required]
    public string Name { get; set; }

    [Required]
    public int Age { get; set; }
}

Notice how we put the validation rules via the data annotations.

We use it in our creation view:

[HttpGet]
public ActionResult CreateDog()
{
    CreateRobotDogViewModel vm = new CreateRobotDogViewModel();

    return View(vm);
}

We use the ViewModel as the page model:

@model WebApplication2.Models.CreateRobotDogViewModel
@using (Html.BeginForm())
{
    <div>
        @Html.TextBoxFor(model => model.Name)

        @Html.TextBoxFor(model => model.Age)

        <input type="submit" value="Create" class="btn btn-default" />
    </div>
}

And, at last, we use the viewmodel to create our model for storing our new robot dog.

[HttpPost]
public ActionResult CreateDog(CreateRobotDogViewModel vm)
{
    if (!ModelState.IsValid)
    {
        ModelState.AddModelError("", "Error!");
        return View(vm);
    }

    RobotDog robotDog = new RobotDog
    {
        Name = vm.Name,
        Age = vm.Age,
        DateCreation = DateTime.Now
    };

    //Add robotDog to the db
}

And that’s it.

Follow us on Twitter to remain updated with the last tutorials!

Doubts? Feel free to leave a comment!