Get SelectedValue from List<SelectListItem> DDL - asp.net-mvc

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.

Related

insert drop down list value in database in asp.net mvc

i want insert drop down list value in database from controller:
public ActionResult PostMessage(ViewModel vm)
{
Models.Message messagetoPost = new Models.Message();
ViewBag.Userlist = new SelectList(dbContext.Users, "Id", "UserName");
ViewBag.Userlist = messagetoPost.MessageTosend;
dbContext.Messages.Add(messagetoPost);
dbContext.SaveChanges();
}
View
#Html.DropDownList("Userlist", null, htmlAttributes: new { #class = "form-control" })
You are using the wrong signature. You need the selected value in your ViewModel, for example UserId:
#Html.DropDownList("UserId", ViewBag.Userlist, null, htmlAttributes: new { #class = "form-control" })
or better yet
#Html.DropDownListFor(m => m.UserId, ViewBag.Userlist, "Select User", htmlAttributes: new { #class = "form-control" })
Finally, you have some other errors (assuming this is the POST method where you want to save). Copy the posted viewmodel fields into your Message entity and save (if no errors):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PostMessage(ViewModel vm)
{
if (ModelState.IsValid)
{
Models.Message messagetoPost = new Models.Message
{
UserId = vm.UserId;
... other fields
};
dbContext.Messages.Add(messagetoPost);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
// Failed, reset dropdown and return view with errors...
ViewBag.Userlist = new SelectList(dbContext.Users, "Id", "UserName");
return View(complianceItemViewModel);
}
#Html.DropDownList("Userlist", null, htmlAttributes: new { #class = "form-control" })
change
#Html.DropDownList("User",ViewBag.Userlist, null, htmlAttributes: new { #class = "form-control" })
In this Place, "User" is the name of the Dropdown name
ViewBag.UserList is the options for the dropdown list
null is placed .if you need set the selected value of the dropdown
Dropdown Control Name and ViewBag name is same than data not bind properly

Fill a DropDownList in .net

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

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

MVC3 model - how to make it so editorfor is a dropdown?

I am making a MVC4 webapp for peers at 2 colleges to use, and later on I will expand to other schools. In my model I currently have
public string school { get; set; }
I would like it so when I do
#Html.EditorFor(model => model.school)
It would be a drop down of "school 1" and "School 2".
How can I go about doing this cleanly? If I can, I would like to be able to make the change in the model and not have to do anything in the view besides call #Html.EditorFor. If the only way to accomplish this is do something in the view, that is OK as well.
Instead of Html.EditorFor you can use Html.DropDownListFor
#{
var items = new SelectList(new[]
{
new SelectListItem {Text = "School1", Value = "School1"},
new SelectListItem {Text = "School2", Value = "School2"},
}, "Text", "Value");
}
#Html.DropDownListFor(x => x.school, #items)
Either you can use above code or you can go with this code in your page.
#Html.DropDownListFor(model => model.Status, new List<SelectListItem>
{
new SelectListItem{ Text="New", Value = "New" },
new SelectListItem{ Text="InProcess", Value = "InProcess" },
new SelectListItem{ Text="Completed", Value = "Completed" },
new SelectListItem{ Text="Rejected",Value="Rejected"},
}, "Select Status", new { #class = "form-control select2_demo_4" })
This will surely help you out and you can get value in your model when you select any of it.

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