0

I've tried to follow a few examples from here and a couple other resources to just create a very simple member in my viewmodel and display it as a dropdown list on my view with a dropdownlistfor() helper. I can't seem to wrap my head around it and it's not working with what I'm trying.

here's my viewmodel:

public class Car
{
    public int CarId { get; set; }
    public string Name { get; set; }
}

public class MyViewModel
{


    public IEnumerable<Car> Cars = new List<Car> { 
        new Car {
            CarId = 1,
            Name = "Volvo"
        },
        new Car {
            CarId = 2,
            Name = "Subaru"
        }
    };


    public int MyCarId { get; set; }
}

and here is my view:

@Html.DropDownListFor(m => m.MyCarId, new SelectList(Model.Cars, "CarId", "Name"))

and here is my controller:

public ActionResult MyView()
        {
            return View();
        }
tereško
  • 58,060
  • 25
  • 98
  • 150
Christopher Johnson
  • 2,629
  • 7
  • 39
  • 70
  • See http://stackoverflow.com/questions/7142961/mvc3-dropdownlistfor-a-simple-example – mr_plum Sep 18 '12 at 20:09
  • that's actually the example I followed (almost to the letter). Initially I had it set up identically to that but got the same result so I tried pulling out the car class from within the MyViewModel class. Still getting null reference exceptions. – Christopher Johnson Sep 18 '12 at 20:12
  • Can you add your `Controller` code to your question? – Gromer Sep 18 '12 at 20:18
  • added the controller code which, after reading the two responses below, was too vanilla....testing them now. – Christopher Johnson Sep 18 '12 at 20:27

2 Answers2

1

You example works fine, I think you forgot to send MyViewModel in POST Action.

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    return View(model);
}
webdeveloper
  • 17,174
  • 3
  • 48
  • 47
1

You need to make sure you send the Model to your View:

public ActionResult Index()
{
    var myViewModel = new MyViewModel()

    return View(myViewModel);
}

And in your View you need to make sure you're defining your Model:

@model namespace.MyViewModel
Kittoes0124
  • 4,930
  • 3
  • 26
  • 47
  • this got me there thanks much. Question though, I had some other members in my viewmodel (for labels and textboxes etc) that were being rendered just fine w/o passing the in the instance of the viewmodel. Why does the dropdownlist require that the instance be passed in and the others do not? – Christopher Johnson Sep 18 '12 at 20:29
  • @ChristopherJohnson Couldn't tell you that without seeing your full code. – Kittoes0124 Sep 18 '12 at 20:31