0

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

4

1 に答える 1

2

VM をインスタンス化しましたが、その Account プロパティはインスタンス化していません...これを試してください:

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

同じことがビューにも当てはまります。

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

これがおそらくビューに属することはほとんどありませんが。代わりにコントローラーに設定する必要があるもののようです。

于 2012-07-30T03:54:40.847 に答える