Hey I have tried following to set the selected value for dropdownlist.
In My controller:
u.Roles = new List<AspNetRole>();
foreach (var role in db.AspNetRoles)
{
u.Roles.Add(role);
}
And in my View:
#Html.DropDownList(Model.role.Id, new SelectList(Model.Roles, "Id", "Name"), htmlAttributes: new { #class = "form-control"})
But still not working, I did not got the selected value. When debugging I can see that Model.role.Id contains the selected value.
Note also that the Id is of type string, because it is hashed.
What I am doing wrong?
There are few ways of display DropDownList in MVC. I like the following approach.
Note: You need a collection of SelectListItem in model.
Model
public class MyModel
{
public int SelectedId { get; set; }
public IList<SelectListItem> AllItems { get; set; }
public MyModel()
{
AllItems = new List<SelectListItem>();
}
}
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel();
model.AllItems = new List<SelectListItem>
{
new SelectListItem { Text = "One", Value = "1"},
// *** Option two is selected by default ***
new SelectListItem { Text = "Two", Value = "2", Selected = true},
new SelectListItem { Text = "Three", Value = "3"}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Get the selected value
int id = model.SelectedId;
return View();
}
}
View
#model DemoMvc.Controllers.MyModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DropDownListFor(x => x.SelectedId, Model.AllItems)
<input type="submit" value="Submit" />
}
Related
How am I able to select multiple items in a Listbox that will be passed to the controller's Post model parameter?
I'm able to physically select multiple via holding CTRL, but when I submit, I get the validation error message, "The field TagId must be a number." It only submits with one item selected.
Create View Form showing multiple items selected
The List Box
#Html.ListBoxFor(model => model.allTags[0].TagId, new SelectList(Model.allTags, "TagId", "Name"), new { #class = "form-control", #Id = "SelectTags", #style = "width:200px;height:300px;" })
The controller Post method
[HttpPost]
public ActionResult Create(CreateRecipe model)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("ViewRecipes");
}
catch
{
return View();
}
}
Thank you
You can try the following code to select multiple items from ListBoxFor and pass it to controller Post method.
Controller:
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
var model = new UserModel
{
SelectedTeaIds = new[] { 3 },
TeaList = GetAllTeaTypes()
};
return View(model);
}
[HttpPost]
public ActionResult Index(UserModel model)
{
model.TeaList = GetAllTeaTypes();
if (model.SelectedTeaIds != null)
{
List<SelectListItem> selectedItems = model.TeaList.Where(p => model.SelectedTeaIds.Contains(int.Parse(p.Value))).ToList();
foreach (var Tea in selectedItems)
{
Tea.Selected = true;
ViewBag.Message += Tea.Text + " | ";
}
}
return View(model);
}
public List<SelectListItem> GetAllTeaTypes()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "General Tea", Value = "1" });
items.Add(new SelectListItem { Text = "Coffee", Value = "2" });
items.Add(new SelectListItem { Text = "Green Tea", Value = "3" });
items.Add(new SelectListItem { Text = "Black Tea", Value = "4" });
return items;
}
}
Model:
public class UserModel
{
public int[] SelectedTeaIds { get; set; }
public IEnumerable<SelectListItem> TeaList { get; set; }
}
Index.cshtml:
#using WebApplication1.Models
#using System
#model UserModel
#{
ViewBag.Title = "Index";
}
<b>Select Tea Type: </b>
<br />
#using (Html.BeginForm("Index", "Test", FormMethod.Post))
{
<b>Select Tea Type: </b>
<br />
#Html.ListBoxFor(x => x.SelectedTeaIds, Model.TeaList, new { style = "width:200px" })
<br />
<input type="submit" value="submit" />
}
<h4>You Selected</h4>
<b style="color:red">Tea Type: #ViewBag.Message</b>
Result:
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
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. :)
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
I have created a Listbox with asp.net razor. But i want to be able to multiselect the listbox. How do i do that?
I want to use something like this:
[HttpPost]
public ActionResult KenmerkSelectie(List<string> VarFromKenmerk1)
{
}
The following Listbox posts only one variable:
#using (Html.BeginForm("KenmerkSelectie", "KenmerkSelectie", FormMethod.Post, new { id = "kenmerk1" }))
{
#Html.ListBox("VarFromKenmerk1", (SelectList)ViewBag.var)
<input type="submit" value="submit"/>
}
Edit:
I'm trying the following code but I get a error:
#using (Html.BeginForm("KenmerkSelectie", "KenmerkSelectie", FormMethod.Post, new { id = "kenmerk1" }))
{
#Html.ListBoxFor("VarFromKenmerkTEST",(MultiSelectList)ViewBag.var), new {#style = "width: 252px; height: 300px;"})
<input type="submit" value="submit"/>
}
public ActionResult index()
{
ViewBag.VarFromKenmerk1 = new List<SelectListItem>();
ViewBag.VarFromKenmerk1.Add(new SelectListItem
{
Value = "House",
Text = "House"
});
ViewBag.VarFromKenmerkTEST = new MultiSelectList(ViewBag.VarFromKenmerk1);
return View();
}
[HttpPost]
public ActionResult KenmerkSelectie(List<string> VarFromKenmerkTEST){
foreach(var ken in VarFromKenmerkTEST){
//selected items
}
}
Compiler Error Message: CS0411: The type arguments for method
'System.Web.Mvc.Html.SelectExtensions.ListBoxFor(System.Web.Mvc.HtmlHelper,
System.Linq.Expressions.Expression>,
System.Collections.Generic.IEnumerable)'
cannot be inferred from the usage. Try specifying the type arguments
explicitly.
Source Error:
#Html.ListBoxFor("VarFromKenmerkTEST",(MultiSelectList)ViewBag.var),
new {#style = "width: 252px; height: 300px;"})
and I don't know if parameter in KenmerkSelectie is good.
You should use a viewModel to pass the data to your view (strongly typed) and then create your listbox with
#Html.ListBoxFor(viewmodel => viewmodel.model.property, viewmodel.data )
the data attribute of the viewmodel should be a Multiselectlist
viewmodel:
public class viewModel
{
public MultiSelectList data { get; set; }
public Model model { get; set; }
}
You need to set Selected property of SelectList class as well as add attribute new {Multiple = "multiple"}
#{
var VarFromKenmerk1= new List<SelectList> {
new SelectList{ Text = "Text1", Value = "Value1", Selected = true },
new SelectList { Text = "Text2", Value = "Value2" },
new SelectList { Text = "Text3", Value = "Value3", Selected = true }
};
}
#Html.ListBox("VarFromKenmerk1", VarFromKenmerk1, new {Multiple = "multiple"})
I have got a drop downlist that, and i need to set the selected value in a view ,later on when the user selected any item in drop down list , i need to pass that one to model.. I am binding dropdown list in controller like this way ..
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
var itemsforDropdown = new List<SelectListItem> {
new SelectListItem{ Text = "Amount" , Value = "Amount"},
new SelectListItem{Text= "Pound", Value ="Pound"},
new SelectListItem {Text ="Percent", Value ="Percent"}
};
ViewBag.ItemsforDrop = itemsforDropdown;
//ViewData["listitem"] = itemsforDropdown;
return View("DdlCrossFields");
}
and I have got a property in my model like this...
public class CrossFieldValidation
{
[ValueMustbeInRange]
public string DDlList1
{ get; set; }
public string SelectedValue
{ get; set; }
// [Required(ErrorMessage = "Quantity is required")]
[Display(Name = "Quantity:")]
public string TxtCrossField
{ get; set; }
}
and this is my view ...
#using (Html.BeginForm("PostValues", "CrossFieldsTxtboxes"))
{
#Html.ValidationSummary(true)
<div class ="editor-field">
#Html.TextBoxFor(m => m.TxtCrossField)
#Html.ValidationMessageFor(m=>m.TxtCrossField)
</div>
#Html.DropDownList("ItemsforDrop", ViewBag.ItemsforDrop as SelectList,"Select A state", new {id= "State"})
//here i need to get the selected value and i need to pass the this on to model fro future purpose "
<input id="PostValues" type="Submit" value="PostValues" />
}
would any one pls help on this ...
many thanks.....
I'm finding it hard to figure out exactly what you are trying to achieve here but I would set up the page like below.
This way, the CrossFieldValidation is sent to the PostValues with the selected value in the list
Model
public class CrossFieldValidation
{
[ValueMustbeInRange]
public string DDlList1
{ get; set; }
/* add the items list into the model */
public IEnumerable<SelectListItem> Items
{ get; set; }
public string SelectedValue
{ get; set; }
[Display(Name = "Quantity:")]
public string TxtCrossField
{ get; set; }
}
Controller
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
var model = new CrossFieldValidation {
Items = new [] {
new SelectListItem{ Text = "Amount" , Value = "Amount"},
new SelectListItem{Text= "Pound", Value ="Pound"},
new SelectListItem {Text ="Percent", Value ="Percent"}
}
};
return View(model);
}
View
#model CrossFieldValidation
#using (Html.BeginForm("PostValues", "CrossFieldsTxtboxes"))
{
#Html.ValidationSummary(true)
<div class ="editor-field">
#Html.TextBoxFor(m => m.TxtCrossField)
#Html.ValidationMessageFor(m=>m.TxtCrossField)
</div>
#Html.DropDownListFor(m=>m.SelectedValue, new SelectList(Model.Items, "Value", "Text"))
<input id="PostValues" type="Submit" value="PostValues" />
}
In your controller [HttpPost] action add below.
string selectedVal = Request.Form["ItemsforDrop"].ToString();
I have a simple HTML form with dropdwonListFor bound to colors, a textBox below it and submit button to submit the form and save the color.
When I select a color from the dropdownlist, it will change the value of the textbox below it, if the user clicks the submit form. it goes back to the controller and I save the color from the texebox and return view(model) as an action result, but the problem that the dropdownlistfor doesn't get updated with the value of the textbox whether the value in the textbox within the dropdownlist or not.
By the way you can test it urself
Can anybody help please ?
Model.cs
public class TestModel {
public String Color { get; set; }
}
Controller.cs
public ActionResult Index() {
var model = new TestModel();
model.Color="Blue";
ViewData["Colors"]=new List<SelectListItem>() { new SelectListItem() { Text = "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };
return View(model);
}
[HttpPost]
public ActionResult Index(TestModel model) {
model.Color="Red";
ViewData["Colors"]=new List<SelectListItem>() { new SelectListItem() { Text = "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };
return View(model);
}
Index.cs
#using (Html.BeginForm()) {
#Html.DropDownListFor(m => m.Color, ViewData["Colors"], new { #class = "w200" })
<input type="submit" />
}
Model
public class TestModel {
public String Color { get; set; }
public SelectList Colors {get;set;} }
Controller
public ActionResult Index() {
var model = new TestModel();
model.Color="Blue";
var colors =new List<SelectListItem>() { new SelectListItem() { Text = "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "red" } };
model.Colors = new SelectList(colors,"Text","Value");
return View(model);
}
[HttpPost] public ActionResult Index(TestModel model) {
model.Color="Red";
var colors =new List<SelectListItem>() { new SelectListItem() { Text = "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "red" } };
model.Colors = new SelectList(colors,"Text","Value");
return View(model); }
View
#using (Html.BeginForm()) {
<div>
#Html.DropDownListFor(m => m.Color, Model.Colors, new { #class = "w200" })
<input type="submit" />
</div>
}
Okay guys, the problem is not about the way you implement this scenario, the problem here is ModelState. I POST to the Action and return the same view. The second time the view is rendered it will look at the ModelState and use those values to fill the controls.
So simply we need to clear the ModelState before returning the View.
Model.cs
public class TestModel {
public String Color { get; set; }
}
Controller.cs
public ActionResult Index() {
var model = new TestModel();
model.Color="Blue";
ViewData["Colors"]=new List<SelectListItem>() { new SelectListItem() { Text = "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };
return View(model);
}
[HttpPost]
public ActionResult Index(TestModel model) {
model.Color="Red";
ViewData["Colors"]=new List<SelectListItem>() { new SelectListItem() { Text = "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };
***ModelState.Clear();***
return View(model);
}
Index.cs
#using (Html.BeginForm()) {
#Html.DropDownListFor(m => m.Color, ViewData["Colors"], new { #class = "w200" })
<input type="submit" />
}
Cheeeeeers
You need to include all colors in your Post action.
Also do not use ViewData but add the items to you view model:
public class TestModel {
public String Color { get; set; }
IEnumerable<SelectListItem> AvailableColors {get;set;}
}
But since view models are intended to be used to abstract away your models you could do something like:
public class TestModel {
public TestModel(IEnumerable<string> colors)
{
AvailableColors = colors.Select(c => new SelectListItem{Text=c, Value = c});
}
public String Color { get; set; }
IEnumerable<SelectListItem> AvailableColors {get;}
}
And in your controller:
public ActionResult Index() {
var model = new TestModel(new string[]{"Red", "Green", "Blue"});
model.Color="Blue";
return View(model);
}
In order to make the dropdown list change what is selected you have to set the Selected attribute of the select list item corresponding to the textbox value to true. Something like this: (Note: I did not compile and test this. Tweaks may be needed to get it to compile. Also, I assumed that if a color was not in the list it should be added.)
[HttpPost]
public ActionResult Index(TestModel model) {
model.Color="Red";
var colors = new List<SelectListItem>() { new SelectListItem() { Text = "Blue", Value = "Blue" }, new SelectListItem() { Text = "Red", Value = "Red" } };
SelectListItem selectedColor = colors.Where(c => c.Text == model.Color).FirstOrDefault();
if (selectedColor != null)
{
selectedColor.Selected = true;
}
else
{
colors.Add(new SelectListItem() { Text = model.Color; Value = model.Color; Selected = true; };
}
ViewData["Colors"] = colors;
return View(model);
}
EDIT
After doing some testing and digging, it appears that you will need to use javascript to do this as explained in this SO question. Another option is to roll your own helper.