我設法使用ASP.NET MVC 5中的數據庫中的值填充DropDownList。我的目標是將dropDownList的值中的一個賦值給特定模型,並將其發送回數據庫。因此,如果我在下拉列表中保留默認值,則SQL服務器中的數據爲空,這是可以的,但如果我選擇一個選項,則會出現以下錯誤: 拋出異常:System.Web中出現'System.InvalidOperationException'。 Mvc.dll(「沒有類型爲」IEnumerable「的ViewData項具有」狀態「關鍵字。」)。到目前爲止,我嘗試了一切,我打開了一些建議。謝謝 !!! 在控制器:不尋常的行爲DropDownList MVC 5
ViewBag.Status = new SelectList(db.Status, "Id", "Name");
在查看
@Html.DropDownList("Status","Select status...")
在控制器至今..
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Apply(ViewModelVM vm,int x=0)
{
myDb db = new myDb();
ViewBag.SocialStatus = new SelectList(db.SocialStatuses, "Id", "StatusDescription");
return View();
}
[HttpPost]
public ActionResult Apply(ViewModelVM vm)
{
if (ModelState.IsValid)
{
using (myDb db = new myDb())
{
var personalinfo = new PersonalInformation()
{
FirstName = vm.PersonalInformation.FirstName,
LastName = vm.PersonalInformation.LastName,
Birthdate = vm.PersonalInformation.Birthdate,
SocialStatus = vm.SocialStatus
};
ViewBag.SocialStatus = new SelectList(db.SocialStatuses, "Id", "StatusDescription");
db.PersonalInformations.Add(personalinfo);
db.SaveChanges();
}
return View("Success");
}
return View();
}
型號:
public partial class Status
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public SocialStatus()
{
PersonalInformations = new HashSet<PersonalInformation>();
}
public int Id { get; set; }
[StringLength(20)]
public string StatusDescription { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PersonalInformation> PersonalInformations { get; set; }
}
}
視圖模型:
public class ViewModelVM
{
...
public Status SocialStatus { set; get; }
...
}
因爲'Status'的值是'null'(可能是因爲你從POST動作返回視圖)。 –
是的,我願意,但如果是這樣的話,這個問題的解決方案是什麼?我在這個問題上困擾了很多年......我將非常感謝您的幫助:) – FarCry88
您的模型中有一個名爲'Status'的屬性嗎?當前如何在GET方法中填充集合? (你需要顯示相關的代碼) –