2014-02-27 42 views
0

我有家庭控制器動作樣結合:如何做下拉列表中mvc4

public ActionResult Index() 
{ 
    ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 
    List<SelectListItem> oList = new List<SelectListItem>(); 
    oList.Add(new SelectListItem() { Text = "Rest1", Value = "1" }); 
    oList.Add(new SelectListItem() { Text = "Rest2", Value = "2", Selected=true}); 
    oList.Add(new SelectListItem() { Text = "Rest3", Value = "3" }); 
    Person p = new Person() { PossibleSchools = oList }; 
    return View(p); 
} 

另一個都會調用上提交按鈕點擊是::

public void ModelBinding(Person p) 
    { 
     var name = p.Name; 
    } 

鑑於我有下面的代碼::

<div class="content-wrapper"> 
<hgroup class="title"> 
    <h1>@ViewBag.Title.</h1> 
    <h2>@ViewBag.Message</h2> 
</hgroup> 
<form action="Home/ModelBinding" method="post"> 
    <p> 
    Name :: <input type="text" name="Name"/> 
    Restaurant :: @Html.DropDownList("PossibleSchools"); 
     <input type="submit" /> 
</p> 
</form>  
</div> 

而且我的模型是::

public class Person 
{ 
    public string Name { get; set; } 
    public List<SelectListItem> PossibleSchools { get; set; } 
} 

問題是,每當我嘗試調試這個應用程序,我可以看到Name字段被綁定,但PossibleSchools計數爲零。

因此,dropdownlist沒有綁定。

回答

0

這裏有一個重構版本,可能會有所幫助:

在你的控制器:

public ActionResult Index() 
{ 
    ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 
    Person p = new Person(); 
    return View(p); 
} 

public void ModelBinding(Person p) 
{ 
    // Perform action to process the request 
} 

模型:

public class Person 
{ 
    public string Name { get; set; } 
    public string SchoolName { get; set; } 
    public List<SelectListItem> PossibleSchools 
    { 
     get 
     { 
      return new List<SelectListItem>() 
       { 
        new SelectListItem() { Text = "Rest1", Value = "1" }), 
        new SelectListItem() { Text = "Rest2", Value = "2" }), 
        new SelectListItem() { Text = "Rest3", Value = "3" }) 
       }; 
     } 
    } 
} 

最後在你看來:

@model Person 
<div class="content-wrapper"> 
<hgroup class="title"> 
    <h1>@ViewBag.Title.</h1> 
    <h2>@ViewBag.Message</h2> 
</hgroup> 
<form action="Home/ModelBinding" method="post"> 
    <p> 
    Name :: @Html.TextBoxFor(m => m.Name) 
    Restaurant :: @Html.DropDownListFor(model => model.SchoolName, Model.PossibleSchools) 
    <input type="submit" /> 
</p> 
</form>  
</div> 

希望這有助於。

0

在下面的代碼視圖使用的第一行:

@model Person 
<div class="content-wrapper"> 
<hgroup class="title"> 
    <h1>@ViewBag.Title.</h1> 
    <h2>@ViewBag.Message</h2> 
</hgroup> 
<form action="Home/ModelBinding" method="post"> 
    <p> 
    Name :: <input type="text" name="Name"/> 
    Restaurant :: @Html.DropDownListFor(model => model.Name, Model.PossibleSchools) 
     <input type="submit" /> 
</p> 
</form>  
</div>