View List from controller to View - c#

I am just trying out stuff, I have items from different models and want to return them to as one(if its possible).
I have this ActionResult which returns all products from my database:
[HttpGet]
public ActionResult GetAllContents()
{
ViewData["listy"] = GetColors();
var i = (from p in db.tProducts
select p).ToList();
return View(i);
}
and the list is coming from this method
public List<SelectListItem> GetColors()
{
var listy = new List<SelectListItem>();
var colorList = from a in db.tColors
select new SelectListItem
{
Text = a.id.ToString(),
Value = a.name
};
foreach (var item in colorList)
listy.Add(item);
return listy;
}
So how do I display this list as a dropdown on the View?

you can use as below
#Html.DropDownList("listy", ViewData["listy"] as List<SelectListItem>)

You need to parse your object to list of SelectListItem, you can use the following
#Html.DropDownListFor(m => m.Colors, ViewData["listy"] as List<SelectListItem>, "-Colors-", new { })

Related

How can I create a list inside a list with a foreach in c# ?

In other words I need all the elements of list "Categories" to be the "Parent" and elements of list "commodities" be the children.
Example
public string GetCommodities()
{
List<dynamic> categories = new List<dynamic>();
List<dynamic> commodities = new List<dynamic>();
foreach (var comcat in QuickQuoteRepo.CommodityCategories.All().OrderBy(o => o.Order))
{
categories.Add(new
{
comcat.Category,
});
foreach (var com in comcat.Commodities.OrderBy(o => o.Name))
{
commodities.Add(new
{
com.Name,
});
}
}
var response = new JavaScriptSerializer().Serialize(commodities);
return response;
}
And see if it's possible to all commodities names inside each category, within this foreach.
I tried adding a dynamic list such as:
dynamic listOfElements = new { CAT = categories, COMM = commodities };
But it does't return elemnts as parents or dependency of categories. Is the same as adding
commodities.Add(new
{
comcat.Category,
com.Name,
});
public string GetCommodities()
{
List<dynamic> categoryCommodityList = new List<dynamic>();
foreach (var comcat in QuickQuoteRepo.CommodityCategories.All().OrderBy(o => o.Order))
{
var allCommodities = comcat.Commodities.OrderBy(o => o.Name).Select(com => com.Name).ToList();
categoryCommodityList.Add(new { Catagory = comcat.Category, Items = allCommodities } );
}
return new JavaScriptSerializer().Serialize(categoryCommodityList);
}
You class structure does not support parent-child relationships. I mean, if what you want is that each Category holds a list of commodities, then you would need something like this:
var result = from c in comcat
select new { Category = c, Commoddities = c.Commoddities};
This will return a hierarchy of Categories including all Commodities underneath it.
If you are just receiving a flat data set, then you need something like this:
var result = from c in comcat
select new { Category = c,
Commoddities = c.Where(x=>x.Category.Name == c.Name).Select(x=>x.Commodity) };
Hopefully you get the idea...

How to make sure that selectlist items belong to the same SelectListGroup?

I am experimenting with the <optgroup> element and am trying to make several items belong to the same optgroup.
My code:
public async Task<ActionResult> GetStatsView()
{
var users = await _administrationServiceAPI.GetPersons();
var tanks = await _administrationServiceAPI.GetTanks();
var list = new List<SelectListItem>();
foreach (var u in users.Payload)
{
SelectListItem item = new SelectListItem {Text = u.Name, Value = u.Id.ToString(), Group = new SelectListGroup {Name = "Users"} };
list.Add(item);
}
foreach (var u in tanks.Payload)
{
SelectListItem item = new SelectListItem { Text = u.Name, Value = u.Id.ToString(), Group = new SelectListGroup { Name = "Tanks" } };
list.Add(item);
}
#ViewBag.MyList = list;
return View("StatsView");
}
view:
#Html.DropDownList("MyList")
result:
Desiered result is:
Users
UserName
UserName
UserName
Tanks
Tank
Tank
Tank
How do I do this?
To make it work, you need to reuse the SelectListGroup. Just use it like this:
var usersGroup = new SelectListGroup {Name = "Users"};
foreach (var u in users.Payload)
{
SelectListItem item = new SelectListItem {Text = u.Name, Value = u.Id.ToString(), Group = usersGroup };
list.Add(item);
}
And of course similarly for Tanks.
It does not matter that the name is the same, an instance used must be the same in various items to group them into single optgroup.

Set Attribute to ListItem in Linq Query

From list i am populating ListItem for dropdown list.
var list = LoadList();
var listitems = list.Select(l => new ListItem
{
Value = l.Id,
Text = l.Description
Attributes ????
}).ToList();
On the Linq query I want to add attribute. Attributes.Add() method is not accessible. Any idea?
From MSDN, the Attributes property is read only:
[BrowsableAttribute(false)]
public AttributeCollection Attributes { get; }
so you will not be able to do it using the object initialisers.
You could do this by doing something like:
var listitems = list.Select(l => { var li = new ListItem
{
Value = l.Id,
Text = l.Description
}; li.Attributes.Add(....); return li; ).ToList();

How can I save a viewmodel for postback viewing?

I am working on MVC project where I have successfully created a search page with several dropdowns and textboxes. After the user queries the data, they are then transferred to a List page with a list of results corresponding to our search. I was wondering if it is possible to create a button located on the List view that returns them back to the search page, the search page's textboxes/dropdowns still populated with their previous search. Currently, when they return, their previous search was cleared, and they can't see what was queried.
Simplified: Is there a way to capture the data of a viewmodel on query submit, and then be able to access it with simple return button.
Get Method (populates dropdown etc)
[HttpGet]
public ActionResult Index()
{
//testTypes
var testTypesL = new List<string>();
var testTypesQr = from z in db.Results
orderby z.TestType
select z.TestType;
testTypesL.AddRange(testTypesQr.Distinct());
//technicians
var techniciansL = new List<string>();
var techniciansQr = from z in db.Results
orderby z.Technician
select z.Technician;
techniciansL.AddRange(techniciansQr.Distinct());
//engineers
var engineersL = new List<string>();
var engineerQr = from z in db.Results
orderby z.Engineer
select z.Engineer;
engineersL.AddRange(engineerQr.Distinct());
//testStalls
var testStallL = new List<string>();
var testStallQr = from z in db.Results
orderby z.TestStall
select z.TestStall;
testStallL.AddRange(testStallQr.Distinct());
//unit models
var unitModelL = new List<string>();
var unitModelQr = from z in db.Results
orderby z.UnitID
select z.UnitID;
unitModelL.AddRange(unitModelQr.Distinct());
TestDataViewModel obj = new TestDataViewModel();
obj.EngineerList = new SelectList(engineersL);
obj.TechnicianList = new SelectList(techniciansL);
obj.TestStallList = new SelectList(testStallL);
obj.UnitModelList = new SelectList(unitModelL);
obj.TestTypeList = new SelectList(testTypesL);
return View("Index", obj);
}
Post Method: (sends user query to the List view)
[HttpPost]
public ActionResult Index(TestDataViewModel obj)
{
var data = from d in db.Results
select d;
//search data parameters
if (!String.IsNullOrEmpty(obj.StartDate.ToString()) && !String.IsNullOrEmpty (obj.EndDate.ToString()))
{
data = data.Where(z => obj.StartDate <= z.EndDate && obj.EndDate >= z.EndDate);
}
if (!String.IsNullOrEmpty(obj.TestNumber.ToString()))
{
data = data.Where(z => z.TestNumber == obj.TestNumber);
}
if (!String.IsNullOrEmpty(obj.unitModel))
{
data = data.Where(z => z.UnitID == obj.unitModel);
}
if (!String.IsNullOrEmpty(obj.Project))
{
data = data.Where(z => z.ProjectNum.Contains(obj.Project));
}
if (!String.IsNullOrEmpty(obj.testType))
{
data = data.Where(z => z.TestType == obj.testType);
}
if (!String.IsNullOrEmpty(obj.engineer))
{
data = data.Where(z => z.Engineer == obj.engineer);
}
if (!String.IsNullOrEmpty(obj.technician))
{
data = data.Where(z => z.Technician == obj.technician);
}
if (!String.IsNullOrEmpty(obj.testStall))
{
data = data.Where(z => z.TestStall == obj.testStall);
}
return View("List", data);
}

Object reference error adding a new select list item

I'm having a problem with the List<SelectListItem>. Whenever the code hits the foreach it says:
object reference not set to an instance of an object.
Am I missing something or can anyone explain why it is failing there?
public ActionResult HammerpointVideos(string category, string type)
{
var stuff = Request.QueryString["category"];
var ItemId = (from p in entities.EstimateItems
where p.ItemName == category
select p.EstimateItemId).FirstOrDefault();
var Videos = (from e in entities.EstimateVideos
where e.EstimateItemId == ItemId
select new Models.HammerpointVideoModel
{
VideoName = e.VideoName,
VideoLink = e.VideoLink
}).ToList();
var model= new Models.HammerpointVideoListModel();
List<SelectListItem> list = model.VideoList;
foreach (var video in Videos)
{
list.Add(new SelectListItem()
{
Selected=false,
Value = video.VideoLink,
Text = video.VideoName
});
}
}
Is ViedoList initialized before? I assume it is not. Create new list add items to it and after that add reference to it in your model:
var model = new Models.HammerpointVideoListModel();
List<SelectListItem> list = new List<SelectListItem>();
foreach (var video in Videos)
{
list.Add(new SelectListItem()
{
Selected=false,
Value = video.VideoLink,
Text = video.VideoName
});
}
model.VideoList = list;
Probably You didn't initialized VideoList in the parameterless constructor of HammerpointVideoListModel class, so it is NOT an empty list.
Put
VideoList = new List<SelectedListItem>();
in the constructor.

Categories

Resources