Moslem7026 Moslem7026 - 3 months ago 9
C# Question

Choose One Model in List<t> from view and send back to action

As we know we can pass data from controller to views using

ViewData
,
ViewBag
,
TempData
,
Session
And
Model
. I used model to send list of dynamically created List object to View.

Model :

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


Controller :

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


Fill
DropDownList
by binding to
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" />
}


Sending back List of model is possible using
@Html.ActionLink("Index","Index",lstPerson)
, but how do we know which item is selected? What is the best way to catch model that's selected in dropdownlist and send back to controller and work with the selected model in list?

Answer

Model:

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

Controller:

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

View:

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

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

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

Controller post action

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

Send Back List Of Model Is Possible to using @Html.ActionLink("Index","Index",lstPerson).

Actually this is wrong assumption:

  1. Html.ActionLink simply generates a link : <a href="">
  2. Only inputs are posted back to the controller, so if you want to post something it should be rendered as <input> or <select>
Comments