Fill a DropDownList in .net - asp.net-mvc

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

Related

How to add item to a DropDownlistFor which have a Enumerable.Range list items?

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" })

Get SelectedValue from List<SelectListItem> DDL

If I have a method like this:
public static List<SelectListItem> lstPassFail()
{
List<SelectListItem> lstPossiblePassFail = new List<SelectListItem>()
{
new SelectListItem() { Text = "Pass", Value = "Pass" },
new SelectListItem() { Text = "Fail", Value = "Fail" },
};
return lstPossiblePassFail;
}
Then in my Edit Action I do this:
ViewBag.PassFail = ClassName.lstPassFail();
Then in my Edit View I do this:
#Html.DropDownList("PassFail", (List<SelectListItem>)ViewBag.PassFail, "-- Please Select a Result --", htmlAttributes: new { #class = "form-control" } )
Since this record already exists in the database and that field already has a value how do I display that selectedvalue, instead of the DDL selecting the very first option by default?
I know that you can do this with an overloaded method for SelectList, but can this be done in the way I portrayed above?
Any help is appreciated.
I have figured this out.
I changed:
ViewBag.PassFail = ClassName.lstPassFail();
to
ViewBag.PassFail = new SelectList(ClassName.lstPassFail(), "Value", "Text", chosenWTest.PassFail);
Then in my view I changed the dropdownlist to this
#Html.DropDownList("PassFail", null, "-- Please Select a Result --", htmlAttributes: new { #class = "form-control" } )
This saved the value for that field in that record.

Html.DropDownList SelectedValue

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" })

inserting an item to a #Html.DropdownList

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" })

Set dropdown item selected MVC

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());

Resources