我對MVC相當陌生,我試圖擺脫使用WebForms的形式,但有些事情讓我感到困惑,因爲我需要完成某些工作。MVC綁定模型到視圖中的下拉列表
在我看來,「/areas/admin/cars/form.cshtml」我想用@ Html.Dropdownfor,傳遞的這是由CarManufacturer.cs模型中定義我的汽車製造商的列表。我該怎麼做?
我使用NHibernate的 - 不知道如果讓任何不同...
模型;
public class CarManufacturer
{
public virtual int Id { get; set; }
public virtual string Manufacturer { get; set; }
//***do i need the below line?***
public SelectList CarManufacturerList { get; set; }
}
public class CarManufacturerMap : ClassMapping<CarManufacturer>
{
public CarManufacturerMap()
{
Table("CarManufacturers");
Id(x => x.Id, x => x.Generator(Generators.Identity));
Property(x => x.Manufacturer, x => x.NotNullable(true));
}
}
的控制器調用形式是carController.cs
public ActionResult New()
{
//re-susing views for add and edit
return View("Form", new CarsForm
{
IsNew = true,
});
}
public ActionResult Edit(int id)
{
var car = Database.Session.Load<Car>(id);
if (car == null)
return HttpNotFound();
return View("Form", new CarsForm
{
...do stuff here to populate form fields!...
});
}
視圖模型;
public class CarsForm
{
//do I need the below line?
public IList<CarManufacturer> Manufacturers { get; set; }
public bool IsNew { get; set; }//whether add or edit action to be used
public int? CarId { get; set; }
...more fields
}
非常感謝耐心和幫助新的MVC'er!
啊,現在我看看viewbag方法是如何工作的,我認爲我更喜歡將模型傳遞到DDL,這是我遇到的問題! :) 謝謝! –