Binding hardcoded values and databases values into one dropdownlist - asp.net-mvc-3

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

Related

get list from a class to fill taxtbox in other class by linq

how to get just special 2 attributes from a table to other table( and placement in related textbox) by LINQ??
public string srcht(ACTIVITIES sn)
{
db db = new db();
var q = (from i in db.costumers.Where(i => i.id== sn.id)select i.name).ToList();
return q.Single();
}
public string srcht(ACTIVITIES sn)
{
db db = new db();
var q = (from i in db.costumers.Where(i => i.id== sn.id)select i.family).ToList();
return q.Single();
}
i did linq twice to fill 2 textboxes by name and family in other table. can i do it by one LINQ?
So you have an Activity in sn, and you want the Name and the Family of all Customers that have an Id equal to sn.Id.
var result = db.Customers.Where(customer => customer.Id == sn.Id)
.Select(customer => new
{
Name = customer.Name,
Family = customer.Family,
});
In words: in the database, from the table of Customers, keep only those Customers that have a value for property Id that equals the value of sn.Id. From the remaining Customers select the values of Name and Family.
If you expect that there will only be at utmost one such customer (so if Id is the primary key), just add:
.FirstOrDefault();
If you think there will be several of these customers, add:
.ToList();
The result will be an object, or a list of objects of some anonymous type with two properties: Name and Family.
If you want to mix the Name and the Family in one sequence of strings, which I doubt, consider to put the Name and the Family in an array. Result is sequence of arrays of strings. To make it one array of Strings, use SelectMany:
var result = db.Customers
.Where(customer => customer.Id == sn.Id)
.Select(customer => new string[]
{
customer.Name,
customer.Family,
})
.SelectMany(customer => customer);

Select multiple column in Linq using List

I have a DropDownList and I fill it using linq. The code example below is working.
ddlPortal.DataSource = from rows in db.Portals select new
{rows.Id, rows.PortalName};
But I need to use it with List variable. What's the problem about the code below?
ddlPortal.DataSource = new List<string>(from rows in db.Portals select new {rows.Id.ToString(), rows.PortalName});
By the way I need to retrieve two columns for DataValueField and DataTextField of DropDownList .
That's not a List<string> but a list of an anonymous type. Use var:
var dataSource = db.Portals
.Select(rows => new {Id = rows.Id.ToString(),Portal = rows.PortalName} )
.ToList();
ddlPortal.DataSource = dataSource;

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

ASP.NET MVC3 WebGrid Helper and Model Metadata

I'm trying to use the WebGrid html helper in ASP.NET MVC 3 to autogenerate the columns according to the information found in the ModelMetadata. For example the code in a view that accepts a list of objects would be:
var grid = new WebGrid(Model);
#grid.GetHtml(columns: ViewData.ModelMetadata.Properties.Single.Properties
.Select(p => grid.Column(
columnName: p.PropertyName,
header: p.ShortDisplayName
)));
This actually works like a charm (I was surprised it was that easy actually). What happens here is that from the properties of the model I use the ShortDisplayName as the column's header.
The problem? I need to apply a default format to all columns. Basically I want to use the Html.Raw extension for all the data that my grid will display. An attempt would be something like that :
var grid = new WebGrid(Model);
#grid.GetHtml(columns: ViewData.ModelMetadata.Properties.Single.Properties
.Select(p => grid.Column(
columnName: p.PropertyName,
header: p.ShortDisplayName,
format: (item) => Html.Raw(GetPropertyValue(item, p.PropertyName))
)));
where the method GetPropertyValue would read the value of the property using reflection or whatever (I need to remind here that item is dynamic and its value is actually the object that is being displayed in the current row).
Is there any better way to do this?
Thanks,
Kostas
I suggest you looking into MVCContrib Grid project: http://mvccontrib.codeplex.com/wikipage?title=Grid
Don't know if you still need some help with this question, but I had a problem just like yours and that's what I did to solve it:
I Used a Foreach loop to iterate through the properties
Filled a variable with the name of the property
Formated the column
The code that I got was something like this:
var columns = List<WebGridColumn>();
foreach (var p in ViewData.ModelMetadata.Properties.Single.Properties) {
String propertyName = p.PropertyName;
columns.Add(grid.Column(p.PropertyName, p.ShortDisplayName, format: item => Html.Raw(GetPropertyValue(item.Value, propertyName))));
}
#grid.GetHtml(columns: columns.ToArray());
And that's how I get the property's value:
public static object GetPropertyValue(object obj, String propertyName)
{
if (propertyName.Contains("."))
{
int index = propertyName.IndexOf(".");
object prop = obj.GetType().GetProperty(propertyName.Substring(0, index)).GetValue(obj, null);
return GetPropertyValue(prop, propertyName.Substring(index + 1));
}
return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
I really don't know if this is the best way, but it's working pretty good for me.

Resources