从视图中选择List <t>中的一个模型并发送回操作

时间:2015-07-10 04:29:54

标签: c# asp.net-mvc

我们知道,我们可以使用ViewDataViewBagTempDataSessionModel将数据从控制器传递到视图。我使用model将动态创建的List对象列表发送给View。

型号:

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);

通过绑定DropDownList填写Model List

@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 个答案:

答案 0 :(得分: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(&#34;索引&#34;,&#34;索引&#34;,lstPerson)。

实际上这是错误的假设:

  1. Html.ActionLink只需生成一个链接:<a href="">
  2. 只有输入会回发给控制器,因此如果您想发布某些内容,则应将其呈现为<input><select>