No se puede completar 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.

Muchas Gracias

preguntado el 30 de julio de 12 a las 04:07

1 Respuestas

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.

Respondido 30 Jul 12, 22:07

drumboog. Actually I had already done that but got an error and then got side tracked in my trouble shooting (must have been a typo). This is what needs to be done. Thanks for getting me back on track. I also discovered that in order to pass any values set in the controller to the Model sent to the POST action you need to use a @Html.HiddenFor for each property in the input form in the View. @Html.HiddenFor(z => z.Account.Number) - Joe

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.