How can set the selected value of a dropdownlist? When the dropdownlist is binded the selected value/item should be the most recent data that was saved in the database.
Here's What I've got so far:
Controller:
int userid = int.Parse(UserID);
if (!string.IsNullOrEmpty(UserID))
{
IEnumerable<SelectListItem> address = db.Address
.Where(c => c.UserID == userid)
.OrderByDescending(c => c.ID)
.Select(c => new SelectListItem
{
//make drop down list multi line
// display complete address
Value = c.ID.ToString(),
Text = c.StreetName + ", " + c.City
});
ViewBag.AddressID = address;
}
return View();
Controller:
#Html.DropDownList("AddressID", null, "Select Address", new { #class = "dropdown-toggle col-md-9 form-control" })
Try this
In it the Model.values I mentioned about the list you passed.
and the Value defined the value of each option in dropdown.
and the Text defined the Text value that you able to see in the dropdown
and the value i set as 4 id denote the value of selected text from database.
Note: new SelectList(Model.values, "Value", "Text", "4") in it the 4 I defined in here is the value of your selected address. Please pass the value of selected text in the area.
Please try the below code.
#Html.DropDownList("AddressID", new SelectList(Model.values, "Value", "Text", "4"), "Select Address", new { #class = "dropdown-toggle col-md-9 form-control" })
Do the following
int userid = int.Parse(UserID);
if (!string.IsNullOrEmpty(UserID))
{
IEnumerable<SelectListItem> address = db.Address
.Where(c => c.UserID == userid)
.OrderByDescending(c => c.ID)
.Select(c => new SelectListItem
{
//make drop down list multi line
// display complete address
Value = c.ID.ToString(),
Text = c.StreetName + ", " + c.City
});
ViewData["DropDownSource"] = address.ToList();
}
return View();
In the View
#Html.DropDownListFor(model => model.AddressID, new SelectList((System.Collections.IEnumerable)ViewData["DropDownSource"], "Value", "Text", Model.AddressID), "Select Address", new { #class = "dropdown-toggle col-md-9 form-control" })
Related
I write this code to extract specific column to be added into the list, but its wrong. I want to:
List<Stone_Names> Stones = new List<Stone_Names>();
using (PSPlatformEntities1 p = new PSPlatformEntities1())
{
Stones.Add(new SelectListItem
{
Text = p.Stone_Names["stoneName"].ToString(),
Value = p.Stone_Names["nameID"]
});
}
It's very simple get the list from db first the bind into dropdown
ViewBag.DDlist= db.Stones.ToList().Select(x => new
SelectListItem()
{
Text = x.stoneName,
Value = x.nameID.ToString()
});
In view
#Html.DropDownListFor(model => model.modelProperty,
new SelectList(ViewBag.DDlist, "Value", "Text"),
"Select value", new { #class = "form-control" })
Note: stoneName , nameID should be your table name
I have a DropDownListFor with a static selectList
Code:
#Html.DropDownListFor(model => model.FinancialInfo.FinancialExpiryMonth,
new SelectList(Enumerable.Range(1, 12)),
(Model.FinancialInfo == null
|| Model.FinancialInfo.ExpiryDate == null)
? String.Empty
: null,
new { #class = "description-text" })
i need the first item is word Month How can i do that with this static DropDownListFor ?
I'm not sure what you checking in your DropDownListFor but i suggest you to do it this way:
#Html.DropDownListFor(model => model.FinancialInfo.FinancialExpiryMonth,
//Genaration of month names
Enumerable.Range(1, 12).Select(x=> new SelectListItem
{
Value = x.ToString(),
Text = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x)
}),
"Month", //First Value if nothing selected
new { #class = "description-text" })
Finally Solved just to add the selected = true when the item equal the Model Value
#Html.DropDownListFor(model => model.FinancialInfo.FinancialExpiryMonth, Enumerable.Range(1, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x),
}), "Month", new { #class = "description-text" })
I'm trying to retain the selected value of a dropdownlist once the user change the dropdownlist item but its not working as expected what I wanted is to retain the selected item in the dropdownlist but its it defaulted to the Select Company everytime i select the item from dropdownlist, once the user change it postback the page (i know there is no postback in the MVC)
What I'm doing wrong here?
<div class="form-group">
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #id = "form_dropdown" }))
{
#Html.DropDownListFor(m => m.ListOfCompanies,
new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, "Value", "Text"),
"Select Company", new { #class = "form-control", Name = "sel" })
}
[HttpPost]
public ActionResult Index(string sel)
{
var vModel = new EmployeeViewModel();
vModel = _db.GetEmployee.ToList();
//load list of companies:
var company = _db.LoadComapny.ToList();
IEnumerable<SelectListItem> result = model.Select(b => new SelectListItem
{
Value = b.Value,
Text = b.Text,
Selected = b.Text == sel
}).ToList();
vModel.ListOfCompanies = company;
vModel.SELECTED_COMPANY = sel;
return View(vModel);
}
Model:
public class EmployeeViewModel
{
public IEnumerable<SelectListItem> ListOfCompanies { get; set; }
public string SELECTED_COMPANY { get; set; }
//other props
}
DropdownListFor has 2 important argumnets:
the first one the variable with the index of the selected item (mostly lambda expressions (=>) were used)
the secound one is the SelectList of items availble
#Html.DropDownListFor(m => m.SELECTED_COMPANY,
new SelectList(Model.ListOfCompanies, "Value", "Text"),
"Select Company", new { #class = "form-control", Name = "sel" })
Update it to
#Html.DropDownListFor(m => m.SELECTED_COMPANY,
new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, "Value", "Text"),
"Select Company", new { #class = "form-control", Name = "sel" })
This is my current razor code for a simple select.
#Html.DropDownList("Season", Model.Seasons.Select(s => new SelectListItem { Text = s.Name, Value = s.SeasonId.ToString() }), new { #class = "sel_season" })
What I want to do is add/insert an additional option item called "All".
I have tried Concat, but I can't seem to get it to work.
#Html.DropDownList("Season", Model.Seasons.Select(s => new SelectListItem { Text = s.Name, Value = s.SeasonId.ToString() }).Concat( new {"All", "0"}), new { #class = "sel_season" })
The following sample uses an overloaded extension method in the HtmlHelper class:
#Html.DropDownList("Season"
, Model.Seasons.Select(s => new SelectListItem {
Text = s.Name,
Value = s.SeasonId.ToString()
})
, "All"
, new { #class = "sel_season" }
)
Try This
#Html.DropDownList("Season",
Model.Seasons
.Select(s =>
new SelectListItem { Text = s.Name, Value = s.SeasonId.ToString() })
.ToList().Insert(0, SelectListItem { Text = "All",Value = "0"}),
new { #class = "sel_season" })
I have multiple dropdown list for same select list in look and want to set dropdown item selected as per loop.
How can I set specific one item of dropdown list selected in mvc dropdownlist.
Please help.
The Html.DropDownList method takes multiple parameters, one of them being a List<SelectListItem>. The individual instance of the SelectListItem is where you set the Selected property:
var item = new SelectListItem() {
Selected = /* condition */,
Value = "Some Value",
Text = "Some Text"
};
Alternatively:
Create a SelectList collection that exposes the SelectedValue property:
Model.YourSelectList = new SelectList(items /* List<SelectListItem> */,
"Value",
"Text",
37 /* selected value */);
When building the SelectList, you can set the selected item on construction using http://msdn.microsoft.com/en-us/library/dd460123.aspx
Or you can set it on an individual SelectListItem via it's Selected property ( http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.selected.aspx ) and use the single-parameter constructor of the select list, or pass it straight to the DropDownList method.
Use the HTML helper ListBoxFor.
#Html.ListBoxFor(m => m.MyPropertyId, Model.MySelectList)
To build the list of items, you can use the MultiSelectList. For example, in your controller:
public ActionResult Index()
{
// Get a collection of all product id's that should be selected.
int[] productIds = _service.GetSomeProductIds();
// Make a new select list with multiple selected items.
ViewBag.List = new MultiSelectList(
_service.Products,
"Id", // Name of the value field
"Name", // Name of the display text field
productIds ); // list of selected product ids
return View();
}
Then in your view:
#Html.ListBoxFor(m => m.ProductIds, (IEnumerable<SelectListItem>)ViewBag.List)
MVC method to bind custom list to dropdownlist and select item dynamically
if you need more details ,comment below
Create Section
#{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
}
<div class="form-group">
#Html.LabelFor(model => model.SaleOrPurchase, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SaleOrPurchase, list, "-- Select Status --", new {#class= "form-control" })
#Html.ValidationMessageFor(model => model.SaleOrPurchase, "", new { #class = "text-danger" })
</div>
</div>
EDIT Section
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
IEnumerable<SelectListItem> myCollection = list.AsEnumerable();
ViewBag.SaleOrPurchase = new SelectList(myCollection, "Value", "Text", transactionTbl.SaleOrPurchase.ToString().Trim());