Set a selected value by default in List SelectList - c#

I want to set a selected value in my select list by default.
Here I have this select list :
#{
List
<SelectListItem>
dateEcheancierCc = new List
<SelectListItem>
();
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");
}
<div class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche", dateEcheancierCc, new { #class = "form-conrol" })
</div>
}
Here I'am trying to set "Selected-value-by-default" is selected by default but it is not working for me why ?
Here the Dropdownlist:
#Html.DropDownList("DateEche", dateEcheancierCc, new { #class = "form-conrol" })

dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");
change to like this
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });
make sure the item that you set "Selected = true" is the only one in list
I don't know your rule but you can try like this
for example : I have an array { "Jeffrey", "John", "Joe", "Josh" }, and I want set Jeffrey as default selected
if (dateEch == "Jeffrey")
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });
else
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch });

Replace your DropdownList as below,
<div class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche",new SelectList(dateEcheancierCc,"Value","Text","Selected-value-by-default"), new { #class = "form-conrol" })
</div>
and selectList as
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(
new SelectListItem() { Text = dateEch, Value = dateEch }
);
}
https://dotnetfiddle.net/RFgoD1

if your views have model then you can use like this
#Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.SelectCollections, "Value", "Text", Model.ValueToBeSelectedInCollection))

You need to add Selected=true while building the SelectListItem.
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch ,Selected = true });
}

Related

How to set Dropdownlist field in ASP.NET MVC [duplicate]

This question already has answers here:
MVC5 - How to set "selectedValue" in DropDownListFor Html helper
(5 answers)
Closed 5 years ago.
I have a IEnumerable<SelectListItem>
My ViewModel
public class StatusClass
{
public string Status { get; set; }
public IEnumerable<SelectListItem> StatusList { get; set; }
}
I set values in to StatusList from my controller.
StatusClass statusObj = new CRM.StatusClass();
List<SelectListItem> Discountdata = new List<SelectListItem>();
Discountdata.Add(new SelectListItem() { Value = "All", Text = "All" });
Discountdata.Add(new SelectListItem() { Value = "Draft", Text = "Draft" });
Discountdata.Add(new SelectListItem() { Value = "Issued", Text = "Issued" });
Discountdata.Add(new SelectListItem() { Value = "Partial", Text = "Partially Received" });
Discountdata.Add(new SelectListItem() { Value = "Received", Text = "Received" });
Discountdata.Add(new SelectListItem() { Value = "PAID", Text = "Paid" });
Discountdata.Add(new SelectListItem() { Value = "Billed", Text = "Billed" });
statusObj.StatusList = new SelectList(Discountdata, "Value", "Text");
This works fine and my HTML is like this:
#Html.DropDownListFor(model => model.Status, Model.StatusList)
What i want is, I need to set the selected value from the controller when the list get created.
Suppose I have a string like this:
string newwStatus = "Issued";
How can I set it as selected in the SelectListItem.
I tried this, but its not working in my case:
foreach(var item in StatusList)
{
if(item.value == status)
{
item.Selected = true;
}
}
and tries this too:
IEnumerable<SelectListItem> selectList =
from s in StatusList
select new SelectListItem
{
Selected = (s.Value == status),
Text = s.Text,
Value = s.Value
};
I dont know if these are the right way if someone know how to do this, please help.
Thanks in advance.
The Selected property of SelectListItem is ignored when binding to a model property. You need to set the value of your Status property in the GET method before you pass the model to the view
List<SelectListItem> Discountdata = new List<SelectListItem>
{
new SelectListItem() { Value = "All", Text = "All" },
new SelectListItem() { Value = "Draft", Text = "Draft" },
new SelectListItem() { Value = "Issued", Text = "Issued" },
....
};
StatusClass model = new CRM.StatusClass
{
StatusList = Discountdata,
Status = "Issued"
};
return View(model);
and the 2nd option in your <select> element will be selected.
Note that Discountdata is already IEnumerable<SelectListItem> and using new SelectList(Discountdata, "Value", "Text") to create an identical IEnumerable<SelectListItem> is unnecessary extra overhead.
Note also that since you have the same value for both the value attribute and display text, you could simply use
List<string> Discountdata = new List<string>{ "All", "Draft", "Issued", ... };
and in the model constructor
StatusList = new SelectList(Discountdata),
You're binding Status property to the dropdown. So set the value either from database, or in your case, a default value "Issued" like this:
statusObj.Status = "Issued"

Is it possible to add hardcoded option/values in dropdownlist while retrieving a list from database ? MVC 5

I have this code that can retrieve a list from database in dropdownlist. I want to add hardcoded value or option to this.
Controller:
IEnumerable<SelectListItem> items = db.specimentype.Where(model => model.recordstatus == "active").ToList().Select(c => new SelectListItem
{
Value = c.code.ToString(),
Text = c.specimenType
});
ViewBag.specimentypelist = items;
View:
#Html.DropDownListFor(model => model.SpecimenType, new SelectList(ViewBag.specimentypelist, "Value", "Text", Model.SpecimenType), new { #class = "specimendropdown", #style = "height:27px; margin-left: 40px;" })
I want this to be
#Html.DropDownListFor(model => model.SpecimenType, new List<SelectListItem> { Text = "Horizontal", Value = "Horizontal" }, new SelectList(ViewBag.specimentypelist, "Value", "Text", Model.SpecimenType), new { #class = "specimendropdown", #style = "height:27px; margin-left: 40px;" })
You should move your list generation to the controller, like so for instance
model.SelectListOptions= new List<SelectListItem>
{ new SelectListItem() { Text = "DatabaseOption1", Selected = true, Value = "1"}
, new SelectListItem() { Text = "DatabaseOption2", Selected = false, Value = "2"}
, new SelectListItem() { Text = "AddedOption1", Selected = false, Value = "3"} };
And in your view, you can now reference it like so:
#Html.DropDownListFor(x => x.SpecimenType, Model.SelectListOptions, null, new { #class = "specimendropdown", #style = "height:27px; margin-left: 40px;", #disabled = "disabled" })
UPDATE
To account for your database retrieval, there's not much you need to do. You could add the SelectListItems to the list, like so:
IEnumerable<SelectListItem> items = db.specimentype.Where(model => model.recordstatus == "active").ToList().Select(c => new SelectListItem
{
Value = c.code.ToString(),
Text = c.specimenType
}).ToList();
items.Add(new SelectListItem() { Text = "AddedOption1", Selected = false, Value = "3"});
ViewBag.specimentypelist = items;
Just convert the IEnumerable to a List, and use the Add() method to append your options to the list you retrieve from the database.
You can also use the Insert method if you want to put them in at a specific place.

DropDownFor and bool? not working

I use MVC and have a property with bool?.
I want to use a dropdown box for this, so my Model has a List like this:
var YesOrNoTriState = new List<SelectListItem> {
new SelectListItem { Text = "Select", Value = "" },
new SelectListItem { Text = "Yes", Value = true.ToString() },
new SelectListItem { Text = "No", Value = false.ToString() }
};
My model is null, so it has no value but true will be selected...
Here is my Razor Code:
#Html.DropDownListFor(
x => x.MoProVerglasung,
Model.MoProVerglasungDropDown,
new { #class = "form-control" })

DropDownListFor not showing current value MVC

I have a drop down list, but I cannot get to show the current status in the view:
My html:
<div class="form-group">
#Html.LabelFor(model => parts.Status, new { #class = "col-md-4" })
//This shows the status as "New - Dispatch"
#Html.TextBoxFor(model => parts.Status, new { #class = "col-md-8 required-color" })
//This shows as empty , but i want it to show as New - Dispatch
#Html.DropDownListFor(model => parts.Status, parts.StatusList, String.Empty, new { #class = "col-md-8 required-color" })
</div>
I'm getting my data from here:
StatusList = _partsRequestHServices.GetStatusList(parts.PartRequestStatus)
This is my List:
public List<SelectListItem> GetStatusList(string PartRequestStatus)
{
List<SelectListItem> list = new System.Collections.Generic.List<SelectListItem>();
list.Add(new SelectListItem() { Text = "New - Dispatch", Value = "New - Dispatch"});
list.Add(new SelectListItem() { Text = "Exception - Warehouse", Value = "Exception - Warehouse"});
list.Add(new SelectListItem() { Text = "HP Claim", Value = "HP Claim" });
return list;
}
I want to show the current status in the view it works in the TextBoxFor, but not in the DropDownListFor.
Remove Selected = false from your SelectListItems (by using Selected = false, you are explicitly saying that you don't want any of them to be selected):
public List<SelectListItem> GetStatusList(string PartRequestStatus)
{
List<SelectListItem> list = new System.Collections.Generic.List<SelectListItem>();
list.Add(new SelectListItem() { Text = "New - Dispatch", Value = "New - Dispatch" });
list.Add(new SelectListItem() { Text = "Exception - Warehouse", Value = "Exception - Warehouse" });
list.Add(new SelectListItem() { Text = "HP Claim", Value = "HP Claim" });
return list;
}
You need to return a SelectList not a generic List<SelectListItem>(). By returning this kind of list you have the opportunity to set the value of the selected item. Like this:
public List<SelectListItem> GetStatusList(string PartRequestStatus)
{
list.Add(new SelectListItem() { Text = "New - Dispatch", Value = "New - Dispatch", Selected = false });
list.Add(new SelectListItem() { Text = "Exception - Warehouse", Value = "Exception - Warehouse", Selected = false });
list.Add(new SelectListItem() { Text = "HP Claim", Value = "HP Claim", Selected = false });
}
Then consume that like this:
var statuses = GetStatusList("??");
SelectList statusList = new SelectList(statuses , "Id", "Text", selectedValue);
ViewData["Statuses"] = statusList;
Once you have this set up if you are using a custom template for your drop down list make sure your view model property for Status has this attribute:
[UIHint("string-name-of-editor-template")]

ASP.NET MVC Dropdown List From SelectList

I am building the following SelectList in my controller.
var u = new NewUser();
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
});
return u;
And displaying it on my view like this:
#Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions)
It looks like I am giving it a valid set of SelectListItems in what should be a pretty straightforward dropdown list, but instead of getting a valid <option> list with good values and text, I get this:
<select data-val="true" data-val-range="A user type must be selected." data-val-range-max="2" data-val-range-min="1" data-val-required="The UserType field is required." id="UserType" name="UserType" class="input-validation-error">
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
</select>
What gives? As far as I can tell, this should work.
You are missing setting the Text and Value field in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text", 1);
BTW, you can use a list or array of any type... and then just set the name of the properties that will act as Text and Value.
I think it is better to do it like this:
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text");
I removed the -1 item, and the setting of each item selected true/false.
Then, in your view:
#Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")
This way, if you set the "Select one" item and don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).
If you need to set one of the SelectList items as selected, you can use:
u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);
As one of the users explained in the comments:
The 4th option of the SelectList constructor is ignored when binding to a property using DropDownListFor() - it is the property's value that determines what is selected.
Just try this in razor
#{
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Google", Value = "Google"},
new SelectListItem {Text = "Other", Value = "Other"},
}, "Value", "Text");
}
and then
#Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { #class = "css-class" })
or
#Html.DropDownList("ddlDropDownList", selectList, "Default label", new { #class = "css-class" })
Try this, just an example:
u.UserTypeOptions = new SelectList(new[]
{
new { ID="1", Name="name1" },
new { ID="2", Name="name2" },
new { ID="3", Name="name3" },
}, "ID", "Name", 1);
Or
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
},"Value","Text");
var selectList = new List<SelectListItem>();
selectList.Add(new SelectListItem {Text = "Google", Value = "Google"}) ;
selectList.Add(new SelectListItem {Text = "Other", Value = "Other"}) ;

Categories