Adding an extra data text field in SelectList in MVC - asp.net-mvc

I am using a select list to pass text to the checkbox , What I want is to pass the 2 text fields to the checkboxlist , but Select list doesnt have any options to provide 2 or 3 data text field , I tried to customize it like but cant get the Intellisense working :
public ActionResult Create()
{
IProductRepository ProductResp = new ProductRepository();
IQueryable<Object> getAllProducts = ProductResp .GetProductsSelectlist();
List<object> newList = new List<object>();
foreach (var events in getAllProducts)
newList.Add(new
{
Id = getAllProducts.Name, // I cant get .Name or DateAdded Intellisense here
Name = getAllProducts.Name + " " + getAllProducts.DateAdded
});
ViewData["events"] = new SelectList(newList.ToList(), "Id","Name");
return View();
}
ProductRepository
public IQueryable<Object> GetProductssSelectlist()
{
ApexWorldEntities entity = new ApexWorldEntities();
var query = from v in entity.Products
where v.Date > DateTime.Now
select new { ProductID = v.ID, v.Name , v.Date};
return query.OrderBy(v => v.Date);
}

First, create a class to hold your result:
public class ApexWorldResult
{
public int ProductID { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
}
Then, cast your target collection to an actual type:
var query = from v in entity.Products
where v.Date > DateTime.Now
select new ApexWorldResult { ProductID = v.ID, v.Name, v.Date };
In the Create() method, change the IQueryable<Object> declaration to IQueryable<ApexWorldResult>, and it should work for you...

in addition to my comment
what you need to define is instead of object use "SelectListItem"
This is build used for select list items. where you can specify text, value and value.
and
Model Definition:
class FooModel{
public SelectListItem selectList{get;set;}
...
}
And in controller you use:
public ActionResult YourAction(){
FooModel model = new FooModel();
//Define your collection of list items
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem(){Selected = false, Text = "Text", Value = "MyValue"});
//Assign the list to the collection
model.selectList = new SelectList(listItems);
//Pass to the view
return View(model);
}

Related

How to set default value for ASP.NET MVC DropDownList from model

i am new in mvc. so i populate dropdown this way
public ActionResult New()
{
var countryQuery = (from c in db.Customers
orderby c.Country ascending
select c.Country).Distinct();
List<SelectListItem> countryList = new List<SelectListItem>();
string defaultCountry = "USA";
foreach(var item in countryQuery)
{
countryList.Add(new SelectListItem() {
Text = item,
Value = item,
Selected=(item == defaultCountry ? true : false) });
}
ViewBag.Country = countryList;
ViewBag.Country = "UK";
return View();
}
#Html.DropDownList("Country", ViewBag.Countries as List<SelectListItem>)
i like to know how can i populate dropdown from model and also set default value. any sample code will be great help. thanks
Well this is not a great way to do this.
Create a ViewModel that will hold everything you want to be rendered at the view.
public class MyViewModel{
public List<SelectListItem> CountryList {get; set}
public string Country {get; set}
public MyViewModel(){
CountryList = new List<SelectListItem>();
Country = "USA"; //default values go here
}
Fill it with the data you need.
public ActionResult New()
{
var countryQuery = (from c in db.Customers
orderby c.Country ascending
select c.Country).Distinct();
MyViewModel myViewModel = new MyViewModel ();
foreach(var item in countryQuery)
{
myViewModel.CountryList.Add(new SelectListItem() {
Text = item,
Value = item
});
}
myViewModel.Country = "UK";
//Pass it to the view using the `ActionResult`
return ActionResult( myViewModel);
}
At the view, declare that this view is expecting a Model with type MyViewModel using the following line at the top of the file
#model namespace.MyViewModel
And at anytime you may use the Model as you please
#Html.DropDownList("Country", Model.CountryList, Model.Country)
You can't set the default value using Html.DropDownList, if you want to have a default value, the property itself should have a default value.
private string country;
public string Country
{
get { return country ?? "UK"; }
set { country = value; }
}
Then, when the drop down list renders, as long as "UK" is actually a value for one of the options, it will be automatically set to that.
If the DropDownList is filled in the controller and sent to the view via ViewBag, you can do:
ViewBag.MyName = new SelectList(DbContextname.Tablename, "Field_ID", "Description",idtobepresented);

Fill in a DropDownListFor with the Display tag in ASP.NET MVC3

I'm trying to write a helper for my ASP.NET MVC3 website which will be able to return a new SelectList containing all the Description attribute tag of an Enum
For example, with the following enum :
public enum Test
{
[Display(Name = "Membre 1")]
Member1,
[Display(Name = "Membre 2")]
Member2
}
I would like to be able to fill a DropDownListFor with something like :
#Html.DropDownListFor(m => m.MyTest, MyHelper(Test))
(with MyTest is a Test variable).
and I expect my DropDownList contains :
Membre 1
Membre 2
I used to use this working helper :
public static string GetEnumDescription(this Enum value)
{
Type enumType = value.GetType();
var enumValue = Enum.GetName(enumType, value);
MemberInfo member = enumType.GetMember(enumValue)[0];
var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
var outString = ((DisplayAttribute)attrs[0]).Name;
if (((DisplayAttribute)attrs[0]).ResourceType != null)
{
outString = ((DisplayAttribute)attrs[0]).GetName();
}
return outString;
}
... but I can't get it work in a SelectList
How can I modify this to directly "incorporate" it directly in my #Html.DropDownListFor helper ?
I have seen some helper over the Internet, especially here or here, but no one works for me. Does anyone is able to share a short and elegant helper which returns all the Display attributes of the members of an Enum in order to put them in a DropDownListFor ?
The following is what I use. It's a slightly modified version of something I found online at one point. I'd give credit where credit is due, but I don't remember where I found it originally at this point:
public static SelectList ToSelectList(this Enum enumeration)
{
var list = (from Enum d in Enum.GetValues(enumeration.GetType())
select new { Value = Enum.GetName(enumeration.GetType(), d), Text = d.GetDescription() }).ToList();
var selectedValue = (int)Enum.Parse(enumeration.GetType(), Enum.GetName(enumeration.GetType(), enumeration));
return new SelectList(list, "Value", "Text");
}
public static string GetDescription(this Enum en)
{
Type type = en.GetType();
System.Reflection.MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((System.ComponentModel.DataAnnotations.DisplayAttribute)attrs[0]).GetName();
}
return en.ToString();
}
In your view, you'd use it:
#Html.DropDownListFor(m => m.MyEnumProperty, Model.MyEnumProperty.ToSelectList())
For implementing Enum type data, I think the easiest way is to use custom Enum helper and Templates. Below is how I implement them in my project.
1) Create Enum Helper
public static class EnumHelper
{
public static IEnumerable<SelectListItem> GetItems(this Type enumType, int? selectedValue)
{
if (!typeof (Enum).IsAssignableFrom(enumType))
{
throw new ArgumentException("Type must be an enum");
}
string[] names = Enum.GetNames(enumType);
IEnumerable<int> values = Enum.GetValues(enumType).Cast<int>();
IEnumerable<SelectListItem> items = names.Zip(values, (name, value) =>
new SelectListItem
{
Text = GetName(enumType, name),
Value = value.ToString(),
Selected = value == selectedValue
}
);
return items;
}
// Get Display Name
private static string GetName(Type enumType, string name)
{
string result = name;
DisplayAttribute attribute = enumType.GetField(name)
.GetCustomAttributes(false)
.OfType<DisplayAttribute>()
.FirstOrDefault();
if (attribute != null)
{
result = attribute.GetName();
}
return result;
}
public static string GetItemName(this Type enumType, int selectedValue)
{
if (!typeof (Enum).IsAssignableFrom(enumType))
{
throw new ArgumentException("Type must be an enum");
}
var itemName = GetName(enumType, Enum.GetNames(enumType)[selectedValue]);
return itemName;
}
}
2) Create folder call "DisplayTemplates" in Shared folder.
3) Create View inside "DisplayTemmplates". The view will look like below:
#using Demo.Web.Helper
#{
var itemName = typeof(Test).GetItemName((int)Model);
}
4) Create floder call "EditorTemplates" in Shared folder.
5) Create View inside "EditorTemplates". The view will look like below:
#using Demo.Web.Helper
#{
var items = typeof (Test).GetItems((int?)Model);
}
#Html.DropDownList("",items)
Here you have finished all of helper and templates, ready for use. When you want to implement Enum Type data, just use it like below:
Model
public class MyModel
{
public int Id { get; set; }
//
public Test Test { get; set; }
}
View
#Html.DisplayFor(m => m.Test)
or
#Html.EditorFor(m => m.Test)
Hope it helps.

how to select an item in selectlist in view model MVC 4

I am new in mvc 4 but getting progress. I'm getting crazy with something which how i can select an item in select list in view model.
here is my controller code;
ViewBag.DepartmanListesi = new SelectList(VeriTabani.UnvanDepartmanlaris, "UDepId", "Departman");
and in my view model I am listing a diffirent database but in this list one field includes an id of the UnvanDepartmanlaris.instead of showing the id, I want to show name of the id. but what I have tried is not worked. can you please help me.
I searched many things but most of them was about how to set dropdownlist. I couldnt find any answer of my question.
Thank you in advance. I will be waiting for any response
Try this,
Controller
public List<CustomerModel> GetCustomerName()
{
// Customer DropDown
using (dataDataContext _context = new dataDataContext())
{
return (from c in _context.Customers
select new CustomerModel
{
CustomerId = c.CID,
customerName = c.CustomerName
}).ToList<CustomerModel>();
}
}
[HttpGet]
public ActionResult CustomerInfo()
{
var List = GetCustomerName();
ViewBag.CustomerNameID = new SelectList(List, "CustomerId", "customerName");
return View();
}
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
Model
public class CustomerModel
{
public int CustomerId { get; set; }
public string customerName { get; set; }
public List<SelectListItem> customerNameList { get; set; }
}
I'm using following approach. Hope it helps:
Create helper class (I'm having here all my selectlists)
Public static class Helper
{
public static List<SelectListItem> GetList()
{
var result = new List<SelectListItem>();
var ctx = new YourContext();
var items = from n in ctx.Clients
select new SelectListItem
{
Text = n.Client.Name,
Value = n.ClientID.ToString()
};
foreach (var item in items)
result.Add(item);
return result;
}
}
Than in your View:
#Html.DropDownList("GetClients", Helper.GetList())
Works for me.

Entity Framework Generate List<SelectListItem> of unique values from model

I have a model called Roles:
public string CodeRole { get; set; }
public string Organisation { get; set; }
public string LabelRole { get; set; }
CodeRole and LabelRole contain unique values, but the Organisation column contains about 12 categories. I want to generate a dropdown that allows the user to filter by Organisation.
As a result I want to construct a query using Entity Framework that returns some form of list/array/collection I can easily convert into a List<SelectListItem> with both text and value equal to the distinct Organisation values.
I assume the query would look something like this:
_context.Roles.GroupBy(r=> r.Organisation)
This returns an IGrouping<string,Roles> object, but I don't know how to use the IGrouping.
This would allow me to pass the List<SelectListItem> via a ViewBag to a dropdown list in the view.
Edit: Final Solution based of Alexander Manekovskiy response
List<Roles> orgs = (List<DimRoles>)_context.Roles.GroupBy(f => f.Organisation).Select(r => r.FirstOrDefault()).ToList();
List<SelectListItem> items = new List<SelectListItem>();
foreach (DimRoles r in orgs)
items.Add(new SelectListItem { Text = r.Organisation, Value = r.Organisation });
Yes, you are right about GroupBy, but then you will need to select only first values from groups:
_context.Roles.GroupBy(r=> r.Organisation).Select(r = r.First())
Another possible solution is to use Distinct extension method:
_context.Roles.Select(r=> r.Organisation).Distinct()
Then to get List<SelectListItem> you can use Select:
_context.Roles.GroupBy(r=> r.Organisation).Select(r =>
{
var organization = r.First();
return new SelectListItem() { Name = organization , Value = organization }
}).ToList();
But personally, I would prefer to have another extension method for converting IEnumerable<T> to List<SelectListItem>. This could be something like:
public static IEnumerable<SelectListItem> GetList<TEntity>(this IEnumerable<TEntity> collection, Expression<Func<TEntity, object>> keyExpression,
Expression<Func<TEntity, object>> valueExpression, object selectedValue = null)
{
var keyField = keyExpression.PropertyName();
var valueField = valueExpression.PropertyName();
return new SelectList(collection, keyField, valueField, selectedValue).ToList();
}
Then you can use it like this:
_context.Roles.Distinct(new OrganizationEqualityComparer()).GetList(o => o.Organization, o => o.Organization);
But in this case you will need to implement IEqualityComparer<Role> which is pretty simple:
class RoleOrganizationComparer : IEqualityComparer<Role>
{
public bool Equals(Role x, Role y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x.Organization == y.Organization;
}
public int GetHashCode(Role role)
{
//Check whether the object is null
if (Object.ReferenceEquals(role, null)) return 0;
//Get hash code for the Name field if it is not null.
return role.Organization == null ? 0 : role.Organization.GetHashCode();
}
}

Drop down list value returns to ---select--- after page refresh

So in my application the user will select a name from the drop down list, click 'view' and the corresponding values will display on page.
A hyperlink is then used to sort the list in ascending order. For this to happen the page refreshes and displays the new order of the list.
The value of the drop down list returns back to its original value of 'select' instead of remaining the name of the person selected.
My Model:
public class HolidayList
{
public List<Holiday> HList4DD { get; set; }
public List<Person> PList4DD { get; set; }
public int currentPersonID { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
public HolidayList()
{
HList4DD = new List<Holiday>();
PList4DD = new List<Person>();
}
}
}
my controller:
[HttpPost]
public ViewResult Index(int HolidayDate)
{
var holidays = db.Holidays.Include("Person");
HolidayList model = new HolidayList();
model.currentPersonID = HolidayDate;
model.PList4DD = db.People.ToList();
model.Categories = holidays.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Person.Name
}
);
int data = HolidayDate;
model.HList4DD = db.Holidays.Where(h => h.PersonId == HolidayDate).ToList();
return View(model);
}
[HttpGet]
public ViewResult Index(string sortOrder, int? currentPersonID)
{
var holidays = db.Holidays.Include("Person");
HolidayList model = new HolidayList();
//not null
if (currentPersonID.HasValue)
{
model.currentPersonID = currentPersonID.Value;
}
else
{
model.currentPersonID = 0;
}
model.PList4DD = db.People.ToList();
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "date" : "";
var dates = from d in db.Holidays
where d.PersonId == currentPersonID.Value
select d;
switch (sortOrder)
{
case "date":
dates = dates.OrderBy(p => p.HolidayDate);
break;
}
model.HList4DD = dates.ToList();
return View(model);
}
my view
i've tried a number of different attempts here, the following code worked but has the drop list problem
#Html.DropDownListFor(model => model.HList4DD.First().HolidayDate,
new SelectList(Model.PList4DD, "Id", "Name"),
// Model.currentPersonID
"---Select---"
) *#
my attempts to resolve this are:
#Html.DropDownList("HolidayDate", Model.Categories, "---Select---")
#Html.DropDownListFor("HolidayDate", x => x.HolidayDate, Model.Categories)
Any help much appreciated
You are binding the DropDownFor to a wrong property.
Basically what you want to do is in your Model, create a new Property to bind the value selected by the dropdown.
public int SelectedDate {get;set;}
Then in your code front you wanted to use dropdownFor to bind the property like this
#Html.DropDownListFor(model => model.SelectedDate ,
new SelectList(Model.PList4DD, "Id", "Name"),
// Model.currentPersonID
"---Select---"
)
Not this.
#Html.DropDownListFor(model => model.HList4DD.First().HolidayDate ,
new SelectList(Model.PList4DD, "Id", "Name"),
// Model.currentPersonID
"---Select---"
)
Finnaly, in the action that you wanted to do the sorting, you will need to pass the SelectedDate into the action. Then before you returning it, assign it to Model. And the whole thing will work like magic.

Resources