Search code examples
asp.net-mvc-3asp.net-mvc-viewmodel

Can't populate ViewModel


MVC3 project.

I have several classes: Account, Address, Phone etc. which I set up in a view model

namespace ViewModels
{
  public class AccountVM
  {
    public Account Account { get; set; }
    public Address Address { get; set; }
    public Phone Phone { get; set; }       }

In the controller GET action I just call the view

  public ActionResult Create()
  { return View(); }

In the View I pass the View Model

@model AccountVM

I then use @Html.EditorFor's to populate all the fields and successfully pass it to the POST Action and create the records in the db. So all that code is working.

@Html.EditorFor(z => z.Account.Number)

The problem arises when I try and pre-populate some of the properties. I do the following in the GET action.

    public ActionResult Create()
    { var viewModel = new AccountVM();
      viewModel.Account.Number = 1000000;
      return View(viewModel); }

The code passes Intellisense but when I run I get the "NullReferenceException was unhandled by user code - Object reference not set to an instance of an object" error.

I get the same error if I try and populate using code in the View.

@{ Model.Account.Number = 1000000; }

I need to be able to programatically populate properties in both the controller and the View. I've read several SO posts on how to populate a view model in the controller and modeled my code on them but for some reason my code is not working. What am I'm doing wrong here? How should I go about it in both the Controller and the View? I get that the objects are null when created but can't figure out how to get around that.

Thanks


Solution

  • You've instantiated the VM, but not its Account property... try this:

    public ActionResult Create()
    {
        var viewModel = new AccountVM();
        viewModel.Account = new Account();
        viewModel.Account.Number = 1000000;
        return View(viewModel);
    }
    

    The same goes for the view:

    @{
        if (Model.Account == null) {
            Model.Account = new Account();
        }
        Model.Account.Number = 1000000;
    }
    

    Though there are few times that this probably belongs in the view. It looks like something that should be set in the controller instead.