Selected value for dropdownlistfor in mvc4 - asp.net-mvc

I have created a ViewBag selectlist in Edit action and set the value to be selected as:
ViewBag.Doors = new SelectList(
new[]
{
new {ID = 1, Name="1-Door"},
new {ID = 2, Name="2-Doors"},
new {ID = 3, Name="3-Doors"},
new {ID = 4, Name="4-Doors"},
new {ID = 5, Name="5-Doors"},
new {ID = 6, Name="6-Doors"},
new {ID = 7, Name="7-Doors"}
},
"ID", "Name", advert.Doors);
But in the view the value for the dropdown is not selected by default.
My view code is:
#Html.DropDownListFor(model => model.Doors, (SelectList)ViewBag.Doors, "--Select--")
#Html.ValidationMessageFor(model => model.Doors)
The property Doors will be numeric 1,2,3,..

How will I do it using Annonymous type in ViewBag ?
Overload
Controller Action Method
public ActionResult DropDownListFor()
{
ViewBag.Doors = new SelectList(
new[]
{
new {Value = 1,Text="1-Door"},
new {Value = 2,Text="2-Door"},
new {Value = 3,Text="4-Door"},
new {Value = 4,Text="4-Door"},
new {Value = 5,Text="5-Door"},
new {Value = 6,Text="6-Door"},
new {Value = 7,Text="7-Doors"}
}, "Value", "Text", 7);
return View();
}
View
#Html.DropDownList("Doors")
How will I do it using SelectListItem?
Action Method
[HttpGet]
public ActionResult DropDownListFor()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Action", Value = "0" });
items.Add(new SelectListItem { Text = "Drama", Value = "1" });
items.Add(new SelectListItem { Text = "Comedy", Value = "2",
Selected = true });
items.Add(new SelectListItem { Text = "Science Fiction", Value = "3" });
ViewBag.MovieType = items;
return View();
}
View
#using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
#Html.DropDownList("MovieType")
}
How will I do it using View Model?
View
#using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
#Html.DropDownListFor(m => m.Id, Model.DDLList, "Please select");
}
Action Method
[HttpGet]
public ActionResult DropDownListFor()
{
return View(new Models.Dropdown());
}
View Model
public class Dropdown
{
public string Id { get; set; }
public List<SelectListItem> DDLList
{
get
{
return new List<SelectListItem>()
{
new SelectListItem
{
Text = "1-Door",
Value = "1",
Selected = true
},
new SelectListItem
{
Selected = false,
Value = "2",
Text = "2-Door"
}
};
}
}
}

Related

MVC5 DropDownListFor not selecting correct value

I realize there are tons of questions on SO about this particular issue, however none of the answers that I've already found are doing quite what I am doing.
View Model
public FreightDiscountViewModel()
{
Sign = new List<SelectListItem>();
States = new List<SelectListItem>();
FreightDiscounts = new List<FreightDiscountModel>();
PopSign();
PopStates();
}
public List<FreightDiscountModel> FreightDiscounts { get; set; }
public List<SelectListItem> States { get; set; }
public List<SelectListItem> Sign { get; set; }
private void PopSign ()
{
Sign.Add(new SelectListItem { Text = "-", Value = "-" });
Sign.Add(new SelectListItem { Text = "+", Value = "+" });
}
private void PopStates ()
{
States.Add(new SelectListItem { Value = "AL", Text = "Alabama" });
States.Add(new SelectListItem { Value = "AK", Text = "Alaska" });
States.Add(new SelectListItem { Value = "AZ", Text = "Arizona" });
States.Add(new SelectListItem { Value = "AR", Text = "Arkansas" });
States.Add(new SelectListItem { Value = "CA", Text = "California" });
States.Add(new SelectListItem { Value = "CO", Text = "Colorado" });
}
}
View
#for (var i = 0; i < Model.FreightDiscounts.Count; i++ )
{
<tr>
<td>#Html.DropDownListFor(x => x.FreightDiscounts[i].State, Model.States, new { #class = "form-control" })</td>
</tr>
}
I am populating my FreightDiscounts list in my view model without issue, and right now for testing, I only have 1 state being returned, Alaska. So the 1 record that being populated in that list has the following info
AK,
US,
50,
0,
+
My question is that when the view loads, the state dropdown for the 1 record is set to Alabama (AL), and not Alaska like I would expect. Does anyone see anything obvious I am missing?\
Edit
JamieD77's answer fixed my problem. I changed my View to the following.
<td>
#Html.DropDownListFor(x => x.FreightDiscounts[i].State,
new SelectList(Model.DStates, "key", "value", Model.FreightDiscounts[i].State), new { #class = "form-control" })
</td>
And I changed my View Model to the following
public Dictionary<String, String> DStates { get; set; }
DStates.Add("AL","Alabama" );
DStates.Add("AK","Alaska" );
try using a SelectList and setting the selected item when you build the dropdownlistfor
#Html.DropDownListFor(x => x.FreightDiscounts[i].State,
new SelectList(Model.States, "Value", "Text", x.FreightDiscounts[i].State),
new { #class = "form-control" })
Possibly because your Text and Value fields are reversed?
Edit: OP has updated his code, they originally were reversed.

#Html.Dropdownlist(x => x.id, new int) not working

How i can make this work
#using (Html.BeginForm())
{
#Html.ValidationSummary()
<p>MYep #Html.DropDownListFor(x => x.Id, new int {
new SelectListItem() {Text = "asdad", Value = "1"},
new SelectListItem() {Text = "dfgdgd", Value = "2"},
new SelectListItem() {Text = "werwrwt", Value = "3"}, "Choose")
<input type="submit" value="Ok" />
}
Or should I make a IEnumerable list before and give it to dropdownlistfor?
Matt's answer is fine, but it looks like you are using a ViewModel, so you should just put this static list into the view model and reference the list in your View.
ViewModel:
public sealed class MyViewModel
{
public int Id { get; set; }
public List<SelectListItem> IdList
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "asdad", Value = "1" },
new SelectListItem { Text = "dfgdgd", Value = "2" },
new SelectListItem { Text = "werwrwt", Value = "3" }
};
}
}
}
View:
#Html.DropDownListFor(x => x.Id, Model.IdList)
You are declaring an object of type int and populating it with a List of SelectListItems, which will not work.
I think you want something like this... You may have to make some modifications if x.Id is an int and all the dropdown values are strings, but I'm not sure.
#Html.DropDownListFor(x => x.Id, new List<SelectListItem> {
new SelectListItem() {Text = "asdad", Value = "1"},
new SelectListItem() {Text = "dfgdgd", Value = "2"},
new SelectListItem() {Text = "werwrwt", Value = "3"}}, "Choose")

The ViewData item that has the key 'MaritalStatus' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>' [duplicate]

This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 6 years ago.
I am populating DropDownList from in-memory data and getting this error on POST.
Error: The ViewData item that has the key 'MaritalStatus' is of type 'System.String' but must be of type 'IEnumerable'.
Controller:-
// GET: /Application/Create
public ActionResult Create()
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem { Text = "Unmarried", Value = "1" });
lst.Add(new SelectListItem { Text = "Married", Value = "2" });
lst.Add(new SelectListItem { Text = "Widow", Value = "3" });
ViewBag.MaritalStatus = new SelectList(lst, "Value", "Text");
return View();
}
// POST: /Application/Create
[HttpPost]
public ActionResult Create(ApplicationForm applicationform)
{
if (ModelState.IsValid)
{
db.ApplicationForms.Add(applicationform);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(applicationform);
}
View:-
<div class="editor-label">
#Html.LabelFor(model => model.MaritalStatus)
</div>
<div class="editor-field">
#Html.DropDownList("MaritalStatus")
#Html.ValidationMessageFor(model => model.MaritalStatus)
</div>
Model Property:-
[DisplayName("Marital Status")]
public string MaritalStatus { get; set; }
Any help is appreciated.
Well, i solved this by repopulating the List in POST action, here is the complete working code.
//
// GET: /Application/Create
public ActionResult Create()
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem { Text = "Unmarried", Value = "Unmarried" });
lst.Add(new SelectListItem { Text = "Married", Value = "Married" });
lst.Add(new SelectListItem { Text = "Widow", Value = "Widow" });
ViewBag.MaritalStatus = new SelectList(lst, "Value", "Text");
return View();
}
//
// POST: /Application/Create
[HttpPost]
public ActionResult Create(ApplicationForm applicationform)
{
if (ModelState.IsValid)
{
db.ApplicationForms.Add(applicationform);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem { Text = "Unmarried", Value = "1" });
lst.Add(new SelectListItem { Text = "Married", Value = "2" });
lst.Add(new SelectListItem { Text = "Widow", Value = "3" });
ViewBag.MaritalStatus = new SelectList(lst, "Value", "Text");
}
return View(applicationform);
}

The selected item does not display when I use DropDownListFor

I am using the following to generate a drop down list:
#for (var index = 0; index < Model.AdminSummaries.Count(); index++)
{
<div class="rep_tr0">
<div class="rep_td0">
#Html.DropDownListFor(x => Model.AdminSummaries[index].Status,
AdminStatusReference.GetAdminStatusOptions(),
new { id = string.Format("Status_{0}",index ) })
</div>
</div>
}
Here's the HTML it generates:
<select id="Status_1" name="AdminSummaries[1].Status"><option value="1">Released</option>
<option value="2">Review</option>
<option value="3">New</option>
</select>
Here's the class that gives the status options.
public static class AdminStatusReference
{
public static IEnumerable<SelectListItem> GetAdminStatusOptions()
{
return new[]
{
new SelectListItem { Value = "1", Text = "Released" },
new SelectListItem { Value = "2", Text = "Review" },
new SelectListItem { Value = "3", Text = "New" }
};
}
}
Everything works good EXCEPT it doesn't select the items correctly. There's no option with 'selected' to match the data in the AdminSummaries.
How can I make it so the correct select list items are selected?
Just to clarify this. My problem is that if there is a data record with a value of 3 for the status then when I look at the screen I see a select list with the word "Release" showing.
What I need is for the select list to show text that corresponds with the data value.
Here is the more accurate answer
public static class AdminStatusReference
{
public static IEnumerable<SelectListItem> GetAdminStatusOptionsFor(AdminSummaries arg)
{
var options = new[]
{
new SelectListItem { Value = "1", Text = "Released" },
new SelectListItem { Value = "2", Text = "Review" },
new SelectListItem { Value = "3", Text = "New" }
};
options.First(o=> o.Value == arg).Selected = true;
return options;
}
}
Set the SelectListItem.Selected property to true:
public static class AdminStatusReference
{
public static IEnumerable<SelectListItem> GetAdminStatusOptions()
{
return new[]
{
new SelectListItem { Value = "1", Text = "Released", Selected = true },
new SelectListItem { Value = "2", Text = "Review" },
new SelectListItem { Value = "3", Text = "New" }
};
}
}
It seams from the source code that the DropDownListFor method (actually the ViewDataEvaluator.Eval method) doesn't support expressions containing indexers. Because your expression: AdminSummaries[index].Status contains an indexer that's why the framework doesn't use the selected value from your model class.
The only solution is to specify the selected item when setting the SelectListItem collection, you can do this by passing the currently selected value to your GetAdminStatusOptions method:
View:
#Html.DropDownListFor(x => Model.AdminSummaries[index].Status,
AdminStatusReference.GetAdminStatusOptions(Model.AdminSummaries[index].Status),
new { id = string.Format("Status_{0}",index ) })
A sample GetAdminStatusOptions implementation:
public static IEnumerable<SelectListItem> GetAdminStatusOptions(string selected = null)
{
var options = new[]
{
new SelectListItem {Value = "1", Text = "Released"},
new SelectListItem {Value = "2", Text = "Review"},
new SelectListItem {Value = "3", Text = "New"}
};
foreach (var option in options)
{
option.Selected = option.Value == selected;
}
return options;
}

Bind Html.DropDownList with static items

I have to bind an Html.DropDownList with just two items statically.
Text="Yes" Value="1"
Text="No" Value="0"
The important thing is that, I have to set the text and value fields.
How can I do this?
I used this is properly working
#Html.DropDownList("Status", new List<SelectListItem>
{
new SelectListItem{ Text="Active", Value = "1" },
new SelectListItem{ Text="Not-Active", Value = "0" }
})
It is a best practice not to create the SelectList in the view. You should create it in the controller and pass it using the ViewData.
Example:
var list = new SelectList(new []
{
new { ID = "1", Name = "name1" },
new { ID = "2", Name = "name2" },
new { ID = "3", Name = "name3" },
},
"ID", "Name", 1);
ViewData["list"]=list;
return View();
you pass to the constratctor: the IEnumerable objec,the value field the text field and the selected value.
in the View:
<%=Html.DropDownList("list",ViewData["list"] as SelectList) %>
Code below assumes you are using razor view engine if not you will need to convert it.
#{
var listItems = new List<ListItem>();
listItems.Add(new ListItem{Text="Yes", Value="1"});
listItems.Add(new ListItem{Text="No", Value="0"});
}
#Html.DropDownListFor(m=>m.SelectedValue, listItem);
You should consider creating the model in your code instead of the view. Also this would be a good candidate for an editor template.
if you want to be alittle explicity then try
#{
var domainsList = new SelectList(new []
{
new SelectListItem { Text = ".Com", Value = ".com", Selected = true },
new SelectListItem { Text = ".Shopping", Value = ".shopping"},
new SelectListItem { Text = ".Org", Value = ".org"},
new SelectListItem { Text = ".Net", Value = ".net"},
new SelectListItem { Text = ".AE", Value = ".ae"},
new SelectListItem { Text = ".Info", Value = ".info"},
}, "Value", "Text");
}
#Html.DropDownList("TopLevelDomains", domainsList)
This solved it for me:
<td>
#{ var RlistItems = new List<SelectListItem>();
RlistItems.Add(new SelectListItem { Text = "Select Room Type", Value = "0" });
RlistItems.Add(new SelectListItem { Text = "Meeting Room", Value = "1" });
RlistItems.Add(new SelectListItem { Text = "Office", Value = "2" });
RlistItems.Add(new SelectListItem { Text = "Cafeteria", Value = "3" });
}
#Html.DropDownListFor(model=>model.FirstOrDefault().RoomType
,RlistItems,RlistItems[item.RoomType.Value].Selected=true )
</td>
<select asp-for="CountryName" asp-items=#(new List<SelectListItem> { new SelectListItem {Text="India",Value="1" } ,new SelectListItem {Text="Japan",Value="2" }} ) class="form-control">
<option>SELECT COUNTRY -- </option>

Resources