2015-07-10 30 views
1

我們知道我們可以從控制器數據傳遞到使用ViewDataViewBagTempDataSessionModel意見。我使用模型將動態創建的List對象列表發送到View。選擇從視圖列表<t>(一個)模型,併發送回動作

型號:

public class Person 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public string family { get; set; } 
    public string Link { get; set; } 
} 

控制器:

List<Person> lstPerson = new List<Person>(); 
lstPerson.Add(new Person() { ID = 1, Name = "n1", Link = "l1" }); 
lstPerson.Add(new Person() { ID = 2, Name = "n2", Link = "l2" }); 
lstPerson.Add(new Person() { ID = 3, Name = "n3", Link = "l3" }); 
lstPerson.Add(new Person() { ID = 4, Name = "n4", Link = "l4" }); 
return View(lstPerson); 

通過結合Model List填充DropDownList

@model List<MvcApplication2.Models.Person> 
<h2>Index</h2> 
@Html.BeginForm("Send Model"){ 

@Html.DropDownList(
    "Foo", 
    new SelectList(
     Model.Select(x => new { Value = x.ID, Text = x.Name }), 
     "Value", 
     "Text" 
    ) 

) 
<input type="submit" value="Send" /> 
} 

發回模型可能使用@Html.ActionLink("Index","Index",lstPerson)的名單,但我們怎麼知道選擇哪個項目?捕獲在下拉列表中選擇的模型併發送回控制器並使用列表中的選定模型的最佳方法是什麼?

回答

1

型號:

public class PeopleViewModel 
{ 
    public List<SelectListItem> People {get;set;} 
    public int SelectedPersonId {get;set;} 
} 

控制器:

public ActionResult People() 
{ 
    List<Person> lstPerson = new List<Person>(); 
    lstPerson.Add(new Person() { ID = 1, Name = "n1", Link = "l1" }); 
    lstPerson.Add(new Person() { ID = 2, Name = "n2", Link = "l2" }); 
    lstPerson.Add(new Person() { ID = 3, Name = "n3", Link = "l3" }); 
    lstPerson.Add(new Person() { ID = 4, Name = "n4", Link = "l4" }); 
    TempData["PeopleList"] = lstPerson; 
    var model = new PeopleViewModel 
    { 
     People = lstPerson.Select(
     p => new SelectListItem{ Value = p.ID.ToString(), Text = p.Name}).ToList() 
    } 
    return View(model); 
} 

查看:

@model PeopleViewModel 
<h2>Index</h2> 
@Html.BeginForm("Send Model"){ 

@Html.DropDownListFor(m=>m.SelectedPersonId,Model.People) 

) 
<input type="submit" value="Send" /> 
} 

控制器後行動

[HttpPost] 
public ActionResult People(PeopleViewModel model) 
{ 
    var peopleList = (List<Person>)TempData["PeopleList"]; 
    var selectedPerson = peopleList.FirstOrDefault(p=>p.ID == model.SelectedPersonId); 
} 

發送返回列表模型可以使用@ Html.ActionLink(「Index」,「Index」,lstPerson)。

其實這是錯誤的假設:

  1. Html.ActionLink只是生成一個鏈接:<a href="">
  2. 只有輸入回發到控制器,所以如果你想發佈的東西應該呈現爲<input><select>
+0

我們有三個值'ID = 4,Name =「n4」,Link =「l4」'訪問選定的ID是否可能,如何訪問模型?值和名稱綁定到下拉列表。主機訪問鏈接? – Moslem7026

+0

假設你的人員列表一致,一旦你得到一個選定的ID你需要從這個列表中選擇一個人與這個ID。直接訪問人員不可能 –

+0

Aha,使用'TempData'存儲模型列表,然後選擇我需要的模型通過選定的Id(索引)。 – Moslem7026

相關問題