2015-07-01 55 views
1

類型,我已經將數據從db綁定到下拉列表。 但是當我嘗試鑑於提交,它表明:具有關鍵'Survey_Group'的ViewData項目類型爲'System.String',但必須是'IEnumerable <SelectListItem>'

具有關鍵的ViewData的項目「Survey_Group」的類型是 「System.String」的,但必須是類型爲「IEnumerable的」。

任何人都可以引導我嗎?謝謝。

型號:

[MaxLength(100)] 
[DisplayName("Owner Groups")] 
public string Survey_Group { get; set; } 

查看:

@Html.LabelFor(model => model.Survey_Group, "Owner Groups") 
@Html.DropDownListFor(model => model.Survey_Group, (SelectList)ViewBag.GroupList) 

控制器:

public ActionResult SURV_Main_Create() 
{ 
    ViewBag.CurrentPage = "create"; 
    var model = new SURV_Main_Model(); 
    ViewBag.GroupList = new SelectList(db.SURV_Group_Model, "Group_ID", "GroupName"); 
    return View(model); 
} 

// POST: /SURV_Main/Create 
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult SURV_Main_Create(SURV_Main_Model surv_main_model) 
{ 
    if (ModelState.IsValid) 
    { 
     var r = new Random(); 
     int randomno = r.Next(1, 1000000); 
     surv_main_model.Survey_Key = "SURV" + DateTime.Now.ToString("yyyyMMddHHmmss") + randomno; 
     surv_main_model.Survey_Creator = User.Identity.Name; 
     db.SURV_Main_Model.Add(surv_main_model); 
     db.SaveChanges(); 
     return RedirectToAction("SURV_Main_Edit", new { id = surv_main_model.Survey_ID }); 
    } 
    return View(surv_main_model); 
} 

回答

2

在你的POST方法,當模特是無效的,返回的觀點,但都沒有賦值爲ViewBag.GroupList(您在DropDownListFor()方法中使用),因此它爲空,因此例外。

在POST方法需要

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult SURV_Main_Create(SURV_Main_Model surv_main_model) 
{ 
    if (ModelState.IsValid) 
    { 
    .... 
    } 
    ViewBag.GroupList = new SelectList(db.SURV_Group_Model, "Group_ID", "GroupName"); // add this 
    return View(surv_main_model); 
} 
相關問題