How to get DropDownList text from selected value via Linq - linq

I am quite new to MVC3, and developing a DropDownListFor which i need to get both value and text for display result purpose. Any ideas on this issue? Thanks!
In my controller:
ViewBag.vehicleSizes = totalGreenCalculator.GreenCalculator.getVehicleFuelEfficiency();
In my Model:
//Datatype: fuelEfficiency = double, vehicleSizes = string
public IEnumerable<SelectListItem> getVehicleFuelEfficiency()
{
var size = new[] {new vehicleSize {fuelEfficiency = 0.0, vehicleSizes = "Choose your vehicle size"},
//and so on
};
return size.Select(a => new SelectListItem() { Text = a.vehicleSizes, Value = a.fuelEfficiency.ToString() });
}
View:
#Html.DropDownListFor(model => model.GreenCalculator.vehicleList[i].fuelEfficiency, (IEnumerable<SelectListItem>)ViewBag.vehicleSizes)

You can recieve IDictionary on controller. Dropdownlist name must match the name of the dictionary.

Your code looks fine. It will generate the dropdownlist from the given values. But it won't preselect the default option. That's because in the first argument you have used a complex expression. If you wanted to preselect some item you could do this:
#Html.DropDownListFor(
x => x.GreenCalculator.vehicleList[i].fuelEfficiency,
new SelectList(
(IEnumerable<SelectListItem>)ViewBag.vehicleSizes,
"Value",
"Text",
Model.GreenCalculator.vehicleList[i].fuelEfficiency
)
)

Related

How can I but this list of database values in my SelectListItem and DropDownList?

Hi I’m trying to use the following approach to creating a list from my database then accessing them in my view. Here’s what I’ve been trying…
var rTypeList = from r in db.Rubrics where r.DepartmentID == 2 select r;
var selectedRubrics = typeList.Select(r => r.Category);
IList <String> rubricsList = selectedRubrics.ToList();
IList<SelectListItem> iliSLI = new List<SelectListItem>();
SelectListItem selectedrubrics = new SelectListItem();
selectedrubrics.Text = "Choose An Option";
selectedrubrics.Value = "1";
selectedrubrics.Selected = true;
iliSLI.Add(selectedrubrics);
ViewData["Options"] = iliSLI;
Then in my view I have: #Html.DropDownList("Options")
This gets my list started but how can I get the values from this list… IList <String> rubricsList = selectedRubrics.ToList();… and add them to my DropDown list?
You have almost figured out the difficult part of your problem.
Here is an explanation...
At the controller side, you need to have a List of SelectListItem type. I have passed this list to my ViewBag.DropDownData, here you could have passed it to your model instead, but I am trying to keep it as simple as possible. So you pass the list to a viewbag.
Controller code
var myList = new List<SelectListItem>
{
new SelectListItem {Text = "Yasser", Value = "YS"},
new SelectListItem {Text = "Vaibhav", Value = "VS"},
new SelectListItem {Text = "Ramanjit", Value = "RS"}
};
ViewBag.DropDownData = myList;
Now in the view using the #Html.DropDownListFor() method, the first argument should be a string/int (depending upon your value) declared in your model which will be later be used when data is posted back to the controller. The second parameter is the List we just prepared, in case if you are using a model then simply pass your model here instead.
Razor View
#Html.DropDownListFor(m => m.ValueSelected, ViewBag.DropDownData as List<SelectListItem>)
There that’s it. Your dropdown is ready to go :), here’s the ouput of my code:
Output
Hope this helps.

Filter SelectListItem value using some condition

I have one SelectListItem for DropDownList. I have to filter based on some condition. If I try adding the condition then its gives me an error like this (LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression). I ll be adding that code here. Please guide me to solve this.
Code
IEnumerable<SelectListItem> IssueId = (from txt in Db.Issues where txt.BibId == BibId
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true,
});
SelectList IssueIds = new SelectList(IssueId, "Value", "Text");
ViewBag.IssueId = IssueIds;
Thanks
Try this:
LINQ2EF does not know ToString() but after AsEnumerable() you'll get a local collection when ToString() is implemented.
IEnumerable<SelectListItem> IssueId =
(from txt in Db.Issues.Where(e => e.BibId == BibId).AsEnumerable()
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true
});
Linq To Sql can't generate TSQL for txt.Id.ToString()
You will need to iterate the result instead after executing the query, or cast to Enumerable as xeondev suggests.
That extension does not seem to be sorted by linq to Entities but you could just do the mapping once you have the issues, e.g.
var issues = (from issue in Db.Issues
where issue .BibId == BibId
select issue ).ToList();
IEnumerable<SelectListItem> IssueId = (from txt in issues
where txt.BibId == BibId
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true,
});

how to show more than one item with SelectList (it's a dropdown) , im using mvc3

this is my code:
ViewBag.idprofesor = new SelectList(db.Profesor, "IDProfesor", "nombre");
this code generate a dropdown that only shows the name (nombre) of the teachers (profesor) in the database, id like the dropdown to show the name and the lastname of the teacher.
You may have to manually create a ist of SelectListItems that manually specify the fields you want. Like so:
List<SelectListItem> professors = new List<SelectListItem>();
foreach(var professor in db.Professors) {
professors.Add( new SelectListItem() { Text = professor.Fn + " " + professor.Ln, Value = professor.Id } );
}
ViewVag.Professors = professors;
Then in your view:
Html.DropDownListFor( m => m.Professor, ViewBag.Professors );
You just have to pass an IEnumerable of SelectListItem to the constructor. Using Linq to select from the Professor collection:
#{
var mySelectList =
db.Professor.Select(prof => new SelectListItem(
Text = prof.lastName + ", " + prof.nombre,
Value = prof.IDProfessor
)
).AsEnumerable();
}
Using Razor, you should be able to create the drop down list like this:
#Html.DropDownList("mydropdownlist", mySelectList)
To bind it to a property in your model, the syntax is slightly different:
#Html.DropDownListFor(model => model.someproperty, mySelectList)

How to Populate ListBoxFor in Mvc3?

I have a list of type stored procedure which have an ID and a Name as data in it.
i have property of int type in model and a list of same stored procedure.
now i want to bind this information into ListBoxFor
in view i have written this
#Html.ListBoxFor(x => x.HobbyId, new MultiSelectList(Model.listHobby, "pkHobbyId", "Hobby"))
but i am getting an error
The parameter 'expression' must evaluate to an IEnumerable when multiple selection is allowed.
Please Help how to bind.
try that
#Html.ListBoxFor(x => x.HobbyId, Model.listHobby.Select(f => new SelectListItem { Text = f.Hobby, Value = f.pkHobbyId.ToString() }), new { Multiple = "multiple" })
listHobby is iEnumerable list on my sample
sorry if i mislead you, rushed to answer but you cannot get the result of the multiselect listbox into a guid or int variable (whatever type is your HoobyId is) you should have an array to grab the result like
public string[] SelectedHobbyIds { get; set; }
so there must be something wrong with your View Models so its better that u would post your view models to be checked
# Chhatrapati Sharma,
In your controller, try this,
ViewData['anyName'] = new SelectList {
Text = , // text from ur function
Value = , // Value from function
Selected = // if required
}
and in view, bind the viewdata like,
<#Html.ListBox("docImages", ((IEnumerable<SelectListItem>)ViewData["anyName"]))
For testing, try a sample selectlist item as follows,
ViewData['anyName'] = new List<SelectListItem>{
new SelectListItem {Text = "First", Value = "0"},
new SelectListItem {Text = "Second"), Value = "1"},
new SelectListItem {Text = "Third", Value = "2"}
};
If this sample works, then check your function "_supp.listDocImages()" and make sure it return IList
#Html.ListBoxFor(x => x.HobbyId, Model.listHobby.Select(f => new SelectListItem { Text = f.Hobby, Value = f.pkHobbyId.ToString() }), new { Multiple = "multiple" })
HobbyId in expression must be ienumerable because you set multi select

MVC3 Drop Down list not selectng selected item

I have a C#.Net MVC3 web app. I am using Drop Down lists all over the place and having success. However, there are two that I am having trouble with. The only difference is that I am creating the SelectLists on the fly in the code rather than using Lookup tables. I use lookup tables for all the other Drop Downs. When I QuickWatch the SelectLists in the code, the correct Item has the Selected property value set to true. However, when the page loads, the item with the Selected property is not displayed. The first item is. Any ideas? This is one of those werid ones. I've tried both ways below. In both cases, the ViewBag.DateToYear and the SelectList DateToYear have the right values and 'Selected' properties set
1)
//Controller
IList<string> dateToYear = new List<string>();
for (int i = 0; i < numberYears; i++)
{
dateToYear.Add(DateTime.Now.AddYears(i).Year.ToString());
}
ViewBag.DateToYear = new SelectList(dateToYear,"2014")
//View
#Html.DropDownList("DateFromYear", (SelectList)ViewBag.DateToYear )
2)
//Controller
SAME as above
//View
List<SelectListItem> DateToYear = new List<SelectListItem>();
foreach (var m in ViewBag.DateToYear)
{
DateToYear.Add(new SelectListItem { Selected = #m.Selected, Value = #m.Text, Text = #m.Text });
}
#Html.DropDownList("DateFromYear", DateToYear)
The problem is, SelectList works as designed. The bug is in the design. You may set the Selected Property in SelctedItem, but this will completely be ignored, if you traverse the list with the GetEnumerator() ( or if Mvc does that for you). Mvc will create new SelectfListItems instead.
You have to use the SelectList ctor with the SelectListItem[], the Text-Name, the Value-Name and the SelectedValue. Be aware to pass as SelectedValue the VALUE of SelectListItem, which you want to be selected, not the SelectListItem itself! Example:
Why not just do in the controller ?
Pseudo code :
//controller
ViewBag.DateToYear = new SelectList(new[]
{
new SelectListItem { Text = "10", Value = "10" },
new SelectListItem { Text = "15", Value = "15" }
new SelectListItem { Text = "25", Value = "25" },
new SelectListItem { Text = "50", Value = "50" },
new SelectListItem { Text = "100", Value = "100" },
new SelectListItem { Text = "1000", Value = "1000" },
}, "SomeText", "Value", "15");
The second option should be selected.
Not sure if this is the case, but I had some problem with dropdownboxes not getting selected a few days ago.
My problem was: I have a #model.Options and I created a #html.dropdownlist("Options", #model.Options, [...]). However, because they had the same name it somehow conflicted. When I used #html.dropdownlist("anythingElse", #model.Options, [...]) it worked fine.
When I QuickWatched return View(model) the selected options seemed to be set correct too, so it took a while to figure that out. Maybe you have the same problem?
Same thing was happening to me too, make sure you do not give same ID as the property name you gave on your Model. That is how I solved this issue...

Resources