how to show more than one item with SelectList (it's a dropdown) , im using mvc3 - asp.net-mvc-3

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)

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.

Binding hardcoded values and databases values into one dropdownlist

I have a drop down list in C# asp.net MVC3 razor engine.
I need to load values to that dropdownlist from one of my tables in my database and some values are hard coded.
So I need to get both kind of values into one dropdown list.
I can do them separately.
This is how my view is :
#Html.DropDownListFor(model => model.MyTransaction.Status, new MultiSelectList(ViewBag.MyStatusId, "ID", "Name"))
My Model where enums are created :
public enum Ntypes{
halfday
casual
}
My Controller :
ViewBag.MyTransaction = db.LeaveTypes.ToList(); //get the table values to drop down
//then even I can get the hard coded values separately ............
ViewBag.MyTansaction = (from NewLeaveTypes t in Enum.GetValues(typeof(Ntypes))
select new { ID = t, Name = t.ToString()).ToList();
But cant get both values into one dropdownlist.
Plzzzz Help.
Thanks...........
You could concatenate the 2 lists together:
var nTypes = Enum
.GetValues(typeof(Ntypes))
.Select(t => new LeaveType { ID = t, Name = t.ToString())
.ToList();
ViewBag.MyTransaction = db.LeaveTypes.ToList().Concat(nTypes);
and then in the view:
#Html.DropDownListFor(
model => model.MyTransaction.Status,
new SelectList(ViewBag.MyTransaction, "ID", "Name")
)

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

Issue To Select/Show DropDown Selected Value At Edit() In Asp.net MVC 3

I Using Two Table User And Location In User Table I having LocationId And When I'm going to edit The User Form Then I need User With There Exact Location In Drop Down.but i didn't get that this is my code Of Controller:-
LogisticsEntities db = new LogisticsEntities();
RegisterModel Reg = new RegisterModel();
var tempUser = (from c in db.Users select new RegisterModel { _UserId = c.UserID, UserName = c.Name, Code = c.Code, Email = c.Email, Phone = c.Phone, JobRole = c.JobRole, StartDate = c.StartDate, EndDate = c.EndDate, LocationId = c.Location }).SingleOrDefault(x => x._UserId == id);
var varLocation = from Ls in db.Locations select Ls;
ViewData["LocationId"] = new SelectList(varLocation.ToList(), "LocationID", "Location1", "2");
if (tempUser != null)
return View(tempUser);
else
return View();
And In My View I Have code: -
#Html.DropDownList("LocationID", (SelectList)ViewData["LocationId"])
Thanx In Advance..
You are using LocationID as both first parameter of the dropdown and inside ViewData. In order to generate a dropdown you need 2 things: the first argument will be used to generate the name attribute of the dropdown and used to bind the value back and the second argument must represent a collection of SelectListItem that will be used to create the options of the dropdown. So try using a different key for the collection:
ViewData["locations"] = new SelectList(varLocation.ToList(), "LocationID", "Location1", "2");
and then:
#Html.DropDownList("LocationID", (SelectList)ViewData["locations"])

How to get DropDownList text from selected value via 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
)
)

Resources