Reputation: 31
Let's say i want to show multiple DropDownList. Values are same but in view they need to be shown as name of Each value and count of all values in dropdown. Please check out the below data and sample of requirement.
ID 1,2,3,4,5
Name A,B,C,D,E
view now should create 5 dropdownlist as [A] ==== [1,2,3,4,5], [B] ==== [1,2,3,4,5] and so on. What is the easiest way to do .Please suggest
Upvotes: 0
Views: 2640
Reputation: 361
The view model
public class CustomViewModel
{
public string A { get; set;}
public string B { get; set;}
public string C { get; set;}
public string D { get; set;}
public string E { get; set;}
}
the controller
public ActionResult Test()
{
List<SelectListItem> lista = new List<SelectListItem>();
lista.Add(new SelectListItem()
{
Text = "1",
Value = "1"
});
lista.Add(new SelectListItem()
{
Text = "2",
Value = "2"
});
lista.Add(new SelectListItem()
{
Text = "3",
Value = "3"
});
lista.Add(new SelectListItem()
{
Text = "4",
Value = "4"
});
lista.Add(new SelectListItem()
{
Text = "5",
Value = "5"
});
ViewBag.list = lista;
return View(new CustomViewModel());
}
[HttpPost]
public ActionResult Test(CustomViewModel customViewModel)
{
//your code
//if return the same view create again the List<SelectListItem>
return View(customViewModel);
}
The view
@model test.Models.CustomViewModel
@{
ViewBag.Title = "Test";
List<SelectListItem> list = ViewBag.list as List<SelectListItem>;
}
<h2>Test</h2>
@using (Html.BeginForm())
{
<div>
@Html.DropDownListFor(model => model.A, new SelectList(list))
</div>
<div>
@Html.DropDownListFor(model => model.B, new SelectList(list))
</div>
<div>
@Html.DropDownListFor(model => model.C, new SelectList(list))
</div>
<div>
@Html.DropDownListFor(model => model.D, new SelectList(list))
</div>
<div>
@Html.DropDownListFor(model => model.E, new SelectList(list))
</div>
}
Hope this can help you
Upvotes: 0
Reputation: 718
What I would do in this situation is take @Matteo1010's suggestion and create a view model. I had to do this recently and so I have a solution readily available.
You'll first want to create a model containing the values you need for the dropdown list; generally these would be something like
public class DropDownA
{
public int id {get;set;}
public string value {get;set;}
public bool IsSelected{get;set;}
}
Now you want a ViewModel with a list of DropDownA
public class MyViewModel
{
List<DropDownA> dropDownA {get;set;}
public IEnumerable<SelectListItem> ddaSLI { get { return new SelectList(dropDownA, "id", "value"); } }
}
Of course, you're going to have to initialize the list
for(int i = 0; i < YourItems.Count; i++)
{
dropDownA.Add(new DropDownA { id = i, value = "something", IsSelected = false});
}
And in the View it's easy to render and there will be model binding
@Html.DropDownListFor(model => model.id, Model.ddaSLI)
Just repeat for any other dropdowns you want and everything should be just fine. :)
Upvotes: 1