2014-11-21 85 views
0

我通過viewbag獲取dropdownlist中的動態值,dropdownlist值顯示正確,但我的問題是張貼,我得到問題插入dropdownlist值在sql server中,請幫我解決這個問題。如何使用mvc 4將dropdownlist viewbag值發佈到sql server?

這是我的模型頁面,

public class RegisterModel 
{ 
    public Prefix Prefix { get; set; } 
} 

public class Prefix 
{ 
    public int? ID { get; set; } 
    public string Name { get; set; }  
} 

這是我的控制器頁,

void BindPrefix() 
{ 
    List<Prefix> lstPrefix = new List<Prefix>() 
    { 
    new Prefix { ID = null, Name = "Select" }, 
    new Prefix { ID = 1, Name = "Mr" }, 
    new Prefix { ID = 2, Name = "Ms" }, 
    new Prefix { ID = 1, Name = "Mrs" }, 
    new Prefix { ID = 2, Name = "Dr" } 
    }; 
    ViewBag.Prefix = lstPrefix; 
} 

public ActionResult Register() 
{ 
    BindPrefix();  
    return View(); 
} 

[HttpPost]  
public ActionResult Register(FormCollection FC) 
{ 
    string Prefix =FC[ViewBag.Prefix]; // here prefix get null value. 
    return view(); 
} 

這是我的看法頁,

@Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.Prefix, "ID", "Name", ViewBag.pef)) 
+0

ViewBag信息對每個請求持續存在,這就是爲什麼您在發佈操作中ViewBag.Prefix等於null的原因。 – bsting 2014-11-21 07:45:55

+0

您查看是基於模型'RegisterModel',所以回發模型'公衆ActionResult註冊(RegisterModel模型)'這將被正確綁定 – 2014-11-21 07:48:13

+0

我使用ActionResult,但我也顯示null,因爲前綴是布爾數據類型 – 2014-11-21 09:03:11

回答

0

如果你想把你選價值,你必須從下拉的名字得到:

string Prefix =FC["Prefix"]; 

目前這樣的:

@Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.Prefix, "ID", "Name", ViewBag.pef)) 

會產生這個網站:

<select id="Prefix_ID" name="Prefix.ID"> 
......... 
......... 
</select> 

和形式收集使用元素名稱會給你的價值。

string Prefix =FC["Prefix.ID"].ToString(); 
+0

它會產生'