Dropdownlistfor selected item not selecting using viewbag - asp.net-mvc

I have dropdownlistfor which is getting populated from viewbag string array
<td>#Html.DropDownListFor(m => Model[i].start_operation, new SelectList(ViewBag.ValidOpers))</td>
<td>#Html.DropDownListFor(m => Model[i].end_operation, new SelectList(ViewBag.ValidOpers))</td>
It is not selecting the selected item based on Model[i].start_operation and end_operation
ViewBag.ValidOpers = new[] { "One", "Two", "Three", "Four"};
Unable to figure out why it is not selecting. I check giving just a Html.DisplayFor(m=>Model[i].start_operation to check if it is getting the values and yes it is getting the value and displaying correctly in the label, but the same value is not getting selected in the dropdownlistfor.

To over-answer your question:
Try first adding a not-mapped member to your model class:
e.g.
[NotMapped]
static public List<SelectListItem> myListOptions { get; set; }
then in the controller you can have
MyNameSpace.Models.MyModel.myListOptions = db.myTable.Select(uA=> new SelectListItem{ Value = uA.myColumn, Text = uA.myColumn}).Distinct().OrderBy(uA=>uA.Text).ToList();
// if you want string constants use:
MyNameSpace.Models.MyModel.myListOptions = new List<SelectListItem>();
MyNameSpace.Models.MyModel.myListOptions.Add(new SelectListItem() {Text = "a", Value = "a"});
MyNameSpace.Models.MyModel.myListOptions.Add(new SelectListItem() {Text = "b", Value = "b" });
then in the view, you use:
<div class="editor-field">
#Html.DropDownListFor(model => model.myField, MyNameSpace.Models.MyModel.myListOptions )
#Html.ValidationMessageFor(model => model.myField)
</div>

Related

How to add class to index.cshtml

I need to create drop down list that includes 5 different cities using yield return new SelectListItem
This is a part of the code in my newly made class called listOfCities
public static IEnumerable<SelectListItem> GetItems()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "City", Value = "City" });
SelectListItem item = new SelectListItem();
yield return new SelectListItem
{
Text = "London",
Value = "London"
};
This is my code in index.cshtml
#Html.DropDownListFor(model => model.City,listOfCities.GetItems())
When I write this code, it gives me:
THE NAME 'listOfCities' DOES NOT EXIST IN THE CURRENT CONTEXT
Where is the problem?
You need to add a using for the namespace for your listOfCities class in the view.
#using My.Namespace;
#Html.DropDownListFor(model => model.City,listOfCities.GetItems())
Or write out the full namespace
#Html.DropDownListFor(model => model.City, My.Namespace.listOfCities.GetItems())

MVC passing list from controller to viewBag

im using a example code to understand viewbag.
here is a bunch of code
in controller :
List<SelectListItem> dropdownItems = new List<SelectListItem>();
dropdownItems.AddRange(new[]{
new SelectListItem() { Text = "Option One", Value = "1" },
new SelectListItem() { Text = "Option Two", Value = "2" },
new SelectListItem() { Text = "Option Three", Value = "3" }});
ViewBag.dropdownItems = dropdownItems;
return View();
in View:
#Html.DropDownList("Types", ViewBag.dropdownItems as List<SelectListItem>)
#Html.ValidationMessageFor(model => model.Types)
the example was using ViewData, i use here viewbag to practice ..
#Html.DropDownList("Types", ViewBag.dropdownItems as List<SelectListItem>) is used for dropdown part.. but what is the use of #Html.ValidationMessageFor(model => model.Types) here..??
i remove #Html.ValidationMessageFor(model => model.Types) and the result is remain same.. My question is what is the actual impact of it and why should we use it ...??
It is not related at all.
When building your models in MVC, you add metadata notations to it like
[Required]
string Name {get; set;}
Now in the view,when you add
#Html.ValidationMessageFor(model => model.Name)
In this place a validation message would show if the name text-input wasn't filled.

Html.DropDownListFor does not select value

I have an action that retrieves data and sends it to a view. In a view I have two dropdown menus.
First drop down shows salutation (such as "Mr.", "Ms.", etc.) and does not select value I sent for some reason. The other dropdown shows language list and correctly selects value I sent to the view. The relevant code in view is shown below.
#Html.DropDownListFor(model => model.Salutation, ViewBag.salutation as IEnumerable<SelectListItem>)
#Html.DropDownListFor(model => model.Language, ViewBag.languages as IEnumerable<SelectListItem>)
In the controller I have the following code to get the dropdown data.
ViewBag.salutation = new List<SelectListItem>() {
new SelectListItem() { Text = "", Value = "" },
new SelectListItem() { Text = "Mr.", Value = "Mr." },
new SelectListItem() { Text = "Ms.", Value = "Ms." },
new SelectListItem() { Text = "Mrs.", Value = "Mrs." }
};
and
var languages = (from l in db.Languages.ToList()
select new SelectListItem()
{
Text = l.Language,
Value = l.LanguageId.ToString()
}).ToList();
languages.Insert(0, new SelectListItem() { Text = "", Value = "" });
ViewBag.languages = languages;
The only difference I could think of is that the languages dropdown has an integer as value, whereas salutation dropdown has text as value. Is this why the salutation dropdown doesn't work? I know I could go through each salutation List<SelectListItem> item and set Selected property based on the value I retrieved from database. But I was hoping there would be a cleaner way to do this.
Any ideas?
Thanks
UPDATE
I decided to do what I did for another project.
IList<SelectListItem> _salutation = new List<SelectListItem>()
{
new SelectListItem() { Value = "", Text = "" },
new SelectListItem() { Value = "Mr.", Text = "Mr." },
new SelectListItem() { Value = "Ms.", Text = "Ms." },
new SelectListItem() { Value = "Mrs.", Text = "Mrs." }
};
// I could put the following in the declaration above, but for testing purposes it's in foreach loop.
foreach (var item in _salutation)
{
// compare to what's retrieved from database
item.Selected = item.Value == _viewData.Salutation;
}
ViewBag.salutation = _salutation;
After foreach loop I output .Value, .Selected property of each item in _salutation and I get all the correct values with one item being selected. Inside the view I did the following.
#foreach (var item in ViewBag.salutation as IEnumerable<SelectListItem>)
{
<b>#item.Value : #item.Text : #item.Selected</b><br />
}
All the correct Text/Values come up but none are Selected! This happens if I output the values after I execute #Html.DropDownListFor(). If I output the ViewBag.salutation before the html helper the correct value is selected.
SOLUTION
I found the following article useful: DropDownListFor with ASP.NET MVC.
Instead of using ViewBag I added the following to the ViewModel. (Showing the part for salutations drop down.)
public class TheViewModel
{
private IList<string> _salutations = new List<string>() { "", "Mr.", "Ms.", "Mrs." };
public IEnumerable<SelectListItem> SalutationItems
{
get
{
var salutations = _salutations.Select(s => new SelectListItem { Value = s, Text= s });
return salutations;
}
}
// The rest of the ViewModel
}
And in the View I have the following.
#Html.DropDownListFor(model => model.Salutation, Model.SalutationItems)
Instead of just supplying the list to the DropDownListFor helper you could provide it a SelectList. The SelectList constructor takes the list and allows you to explicitly set the selected value as well as an overload that lets you specify the Text and Value fields.
#Html.DropDownListFor(model => model.Salutation,
new SelectList(ViewBag.salutation as IEnumerable<SelectListItem>,
"Value", "Text", Model.Salutation))
Try this,
#Html.DropDownListFor(m =>m.DDCountryModel,IEnumerable<SelectListItem>)ViewBag.salutation)
#Html.DropDownListFor(model => model.Language, IEnumerable<SelectListItem>)ViewBag.languages)
Your Model should be like this,
public class Model
{
public IEnumerable<SelectListItem> DDCountryModel{ get; set; }
public IEnumerable<SelectListItem> Language{ get; set; }
}

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