I'm obviously still missing something about how to bind the selected item in a DropDownList.
I set up the SelectList like this in a repository:
public SelectList GetAgencyList(System.Guid donorId, Int32 selected)
{
AgenciesDonorRepository adRepo = new AgenciesDonorRepository();
List<AgenciesDonor> agencyDonors = adRepo.FindByDonorId(donorId);
IEnumerable<SelectListItem> ad = from a in agencyDonors
select new SelectListItem {
Text = a.Agencies.AgencyName,
Value = a.AgenciesDonorId.ToString()
};
return(new SelectList(ad, "Value", "Text", (selected == 0 ? 0 : selected)));
}
Then in the controller, this:
ViewData["AgenciesDonorList"] = repo.GetAgencyList(donorId, ccResult.AgenciesDonors.AgenciesDonorId);
return View(ccResult);
And in the view, this:
<%=Html.DropDownList("AgenciesDonorList", (IEnumerable<SelectListItem>)ViewData["AgenciesDonorList"])%>
In the debugger right before return View(...), I can see the proper item is selected (true) and all others are false. But in the view, the select option never makes it, and the first time is always shown.
Does this have nything to do with my use of int as the selected param?
Thx. Dale
Change GetAgencyList to:
public SelectList GetAgencyList(System.Guid donorId, Int32 selected)
{
AgenciesDonorRepository adRepo = new AgenciesDonorRepository();
List<AgenciesDonor> agencyDonors = adRepo.FindByDonorId(donorId);
var ad = from a in agencyDonors
select new {
Text = a.Agencies.AgencyName,
Value = a.AgenciesDonorId
};
return(new SelectList(ad, "Value", "Text", selected));
}
ad doesn't have to be of type IEnumerable<SelectListItem>. Is AgenciesDonorId Int32?
I would have to agree with LukLed I am not sure what you are doing with the statement: (selected == 0 ? 0 : selected) If I pass in a 0 then it returns 0 and if I pass in something other than 0 then it uses that value.
Edit:
Oh... I see it. Change the cast:
<%=Html.DropDownList("AgenciesDonorList", (IEnumerable<SelectListItem>)ViewData["AgenciesDonorList"])%>
To:
<%=Html.DropDownList("AgenciesDonorList", (SelectList)ViewData["AgenciesDonorList"])%>
Related
I have "Products table" with following fields
PID int,
product_name varchar(),
product_price int
"Cart table" with following fields
cart_ID
user_id
PID
So I want to display cart items of logged in user
For example if user_ID=100 is logged in , then only his cart items should be displayed to him, with all the product details.
Am using asp.net with entity framework
public ActionResult Cart()
{
Products pro = new Products();
Cart cart =new Cart();
var productID=db.cartDetails.Where(pid=>pid.productId==cart.productId && cart.user_id==session["user_ID"]);
return View(db.productsDetails.Where(pid => pid.productId == productID));
}
Now problem arise, "ProductID" being var type i cannot compare it with "pid=>pid.productid".
How to store productid in int List, so that i can compare it with individual productid from product table to show product details?
try to convert it before check
var productID=int.Parse(db.cartDetails.Where(pid=>pid.productId==cart.productId).ProductId);
return View(db.productsDetails.Where(pid => pid.productId == productID));
EDIT
db.cartDetails.Where(pid=>pid.productId==cart.productId
this will return object of product or something so need to change your code in to
var product = db.cartDetails.Where(pid=>pid.productId==cart.productId).FirstOrDefault();
if(product!= null){
return View(db.productsDetails.Where(pid => pid.productId == product.productID));
}
db.cartDetails.Where(pid=>pid.productId==cart.productId) returns a `WhereListIterator<CartDetail>` object.
So you'll need to to do something like -
var productID=db.cartDetails.Where(pid=>pid.productId==cart.productId).FirstOrDefault();
return View(db.productsDetails.Where(pid => pid.productId == productID.productID));
You can try this
Edit :
First thing you can not compare directly session["user_ID"] with int datatype field as you are doing in you comment cart.user_id==session["user_ID"] follow updated code.
var userID = Convert.ToInt32(Session["user_ID"]); //And please check first session is null or not than go ahead.
//Here as you said now you can compare productID and userId as follow.
//And if these both conditions will be satisfied than you will get cartDetails table first record otherwise it will return null value
var cartDetail = db.cartDetails.Where(pid => pid.productId == cart.productId && pid.user_id == userID).FirstOrDefault();
if(cartDetail != Null)
{
return View(db.productsDetails.Where(pid => pid.productId == cartDetail.productID));
}
FirstOrDefault() Returns the first element of a sequence, or a default value if the sequence contains no elements.
My First line code return you int productID if it is not null.
I'm trying to create a list of orders in a custom Controller in a NopCommerce/MVC application and i want the list to be sorted by creationDate and contain total orders for that date and convert these values to string format.
The thing is i don't want an ActionResult displaying a grid in the view like in Admin/Orders. All i want is a List of all paid orders between model.StartDate and model.EndDate that contains two parameters "CreationDateUtc" and TotalOrders". i simply just need a list containing the data of orders sorted by creationdate.
The if i choose StartDate 2014-03-29 and EndDate 2014-04-02 the output i want would look something like this:
List OrdersTotalList with parameters CreationDateUtc and TotalOrders
CreationDateUtc "2014-03-29"
TotalOrders "562"
CreationDateUtc "2014-03-30"
TotalOrders "485"
CreationDateUtc "2014-03-31"
TotalOrders "733"
CreationDateUtc "2014-04-01"
TotalOrders "729"
CreationDateUtc "2014-04-02"
TotalOrders "681
"
I'm trying to access the data by an implementations of OrderList from OrderController in my CustomController. Problem is this method always returns 10 objects when infact the total number of orders within this timespace is 58. When debugging Total = orders.TotalCount are actually showing 58 orders as one int value). Also a gridmodel is used here but i really don't need a gridmodel, i just need the data from the database:
public List OrderList(GridCommand command, OrderListModel model, OrderModel Omodel)
{
DateTime S = new DateTime(2014, 3, 29); //-- Dates for testing
DateTime E = new DateTime(2014, 4, 02);
model.StartDate = S;
model.EndDate = E;
DateTime? startDateValue = (model.StartDate == null) ? null
: (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.StartDate.Value, _dateTimeHelper.CurrentTimeZone);
DateTime? endDateValue = (model.EndDate == null) ? null
: (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.EndDate.Value, _dateTimeHelper.CurrentTimeZone).AddDays(1);
OrderStatus? orderStatus = model.OrderStatusId > 0 ? (OrderStatus?)(model.OrderStatusId) : null;
PaymentStatus? paymentStatus = model.PaymentStatusId > 0 ? (PaymentStatus?)(model.PaymentStatusId) : null;
ShippingStatus? shippingStatus = model.ShippingStatusId > 0 ? (ShippingStatus?)(model.ShippingStatusId) : null;
//load orders
var orders = _orderService.SearchOrders(startDateValue, endDateValue, orderStatus,
paymentStatus, shippingStatus, model.CustomerEmail, model.OrderGuid, command.Page - 1, command.PageSize);
var gridModel = new GridModel<OrderModel>
{
Data = orders.Select(x =>
{
var customerCurrency = _currencyService.GetCurrencyByCode(x.CustomerCurrencyCode);
var totalInCustomerCurrency = _currencyService.ConvertCurrency(x.OrderTotal, x.CurrencyRate);
return new OrderModel()
{
Id = x.Id,
OrderTotal = _priceFormatter.FormatPrice(totalInCustomerCurrency, true, customerCurrency),
OrderStatus = x.OrderStatus.GetLocalizedEnum(_localizationService, _workContext),
PaymentStatus = x.PaymentStatus.GetLocalizedEnum(_localizationService, _workContext),
ShippingStatus = x.ShippingStatus.GetLocalizedEnum(_localizationService, _workContext),
CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc)
};
}),
Total = orders.TotalCount <-- Returns all orders (58) but as an integer
};
var reportSummary = _orderReportService.GetOrderAverageReportLine
(orderStatus, paymentStatus, shippingStatus, startDateValue, endDateValue, model.CustomerEmail);
var profit = _orderReportService.ProfitReport
(orderStatus, paymentStatus, shippingStatus, startDateValue, endDateValue, model.CustomerEmail);
var aggregator = new OrderModel()
{
aggregatorprofit = _priceFormatter.FormatPrice(profit, true, false),
aggregatortax = _priceFormatter.FormatPrice(reportSummary.SumTax, true, false),
aggregatortotal = _priceFormatter.FormatPrice(reportSummary.SumOrders, true, false)
//aggregatordates =
};
List<Order> TotalProductsSold = new List<Order>();
foreach (var o in orders)
{
TotalProductsSold.Add(o);
}
return TotalProductsSold.ToList(); //<-- returns 10 orders containing all order info
}
If i understand correct in order to archive this i have to first search through orders and if their PaymentStatus is Paid. Then create a List in the Method from above. A foreach loop could iterate through orders and add orders to the List, all though i need to specify i only want CreationDate and TotalOrders for that date as parameters in the List.
I know this isn't right but i emagine something similar. The thing is i need a list of order objects and not one object with one value:
List<OrderModel> OrdersTotalList = new List<OrderModel>();
foreach (var o in orders)
{
OrderModel OM = new OrderModel(OM.OrderTotal, OM.CreatedOn);
OrdersTotalList.Add(OM);
}
return OrdersTotalList; //--
Am i completely of or is this the right aproach? I was hoping someone more familiar with NopCommerce knows more about this.
Sorry for all the text
Thank you
Solved.
In order to get a full list of orders you can create a new constructor in IOrderService/OrderService that is of type List instead of IPagedList. The method used for searching orders are called "SearchOrders" and is of type IPagedList. IPagedList contains the property PageSize wich results in only 10 orders.
You can create a new method with same implementation as SearchOrders and change IPagedList to List, remove "int pageIndex" and "int pageSize".
Then use:
_orderService.YourNewConstructor(DateTime? startTime, DateTime? endTime,
OrderStatus? os, PaymentStatus? ps, ShippingStatus? ss, string billingEmail,
string orderGuid)
{
some code...
}
This will give you access to all orders.
var getAllProducts = _productService.GetAllProducts();
if (productstest.Count > 0)
{
model.idproduct.Add(new SelectListItem()
{
Value = "0",
Text = _localizationService.GetResource("Common.All")
});
foreach (var m in getAllProducts)
model.idproduct.Add(new SelectListItem()
{
Value = m.Id.ToString(),
**Text = m.Size.Distinct().ToString(),**
Selected = model.Pid == m.Id
});
}
public virtual IList<Product> GetAllProducts(bool showHidden = false)
{
var query = from p in _productRepository.Table
orderby p.Name
where (showHidden || p.Published) &&
!p.Deleted
select p;
var products = query.ToList();
return products;
}
The issue is even i tried to populate the select list with distinct size using: Text = m.Size.Distinct().ToString(), but it shows the duplicate for instance 100 products are of size 33 cm , the list will populate the dropdownlist in the view with 33cm occuring 100 times , I dont want to show 100 times , just want to show 1 time, Can any one assist me with this issue ?
Presumably you are only trying to show one product of each different size... if so initialising your getAllProducts variable like so will do the trick:
var getAllProducts = _productService.GetAllProducts().GroupBy(p => p.Size).Select(g => g.First());
I have a table that contains a list of EquipmentIDs and another table that has maintenance records.
When the user edits a maintenance record I want there to be a drop down list of all of the equipment IDs from the table.
The dropdown list populates, and it populates with the correct amount of entries, however they all say System.Web.MVC.SelectListItem instead of the value of the ID.
Here is the code that generates the list:
public ActionResult Edit(int id)
{
MaintPerformed maintPerformed = maintPerformedRepository.GetMaintPerformed(id);
IList<EquipmentID> IDs = equipmentIDRepository.GetEquipmentIDAsList();
IEnumerable<SelectListItem> selectEquipList =
from c in IDs
select new SelectListItem
{
//Selected = (c.EquipID == maintPerformed.EquipID),
Text = c.EquipID,
Value = c.Sort.ToString()
};
ViewData["EquipIDs"] = new SelectList(selectEquipList, maintPerformed.ID);
return View(maintPerformed);
}
Here is the entry in the .aspx page for the Dropdown list:
%: Html.DropDownList("EquipIDs") %>
Here is how I am generating the list from the table:
public List<EquipmentID> GetEquipmentIDAsList()
{
return db.EquipmentIDs.ToList();
}
It appears that everything is working correctly with the exception of assigning the text to be displayed in the drop down box.
What am I missing or not thinking correctly about?
SelectList and SelectListItem are actually mutually exclusive. You should be using one or the other. Etiher pass the constructor of SelectList your raw data (IDs) or don't use SelectList at all and just make ViewData["EquipIDs"] your enumerable of SelectListItem. If you go with the latter approach, you will have to tweak your code so that you are setting the selected item in the constructor of SelectListItem (as you had done, but commented out).
Either:
ViewData["EquipIDs"] = new SelectList(IDs, maintPerformed.ID, "EquipID", "Sort");
Or:
IEnumerable<SelectListItem> selectEquipList =
from c in IDs
select new SelectListItem
{
Selected = c.EquipID == maintPerformed.EquipID,
Text = c.EquipID,
Value = c.Sort.ToString()
};
ViewData["EquipIDs"] = selectEquipList;
I have a problem with a selectlist, I have 8 items and 3 of them gets the value selected = true in debug, but the rendered Html the item isnt selected.
What might be wrong?
List<SelectListItem> UsergroupID = (from usg in _ug.GetUsergroups().ToList()
join ug in u.Usergroups
on usg.UsergroupID equals ug.UsergroupID into j
select
new SelectListItem
{
Selected = j.Any(),
Value = usg.UsergroupID.ToString(),
Text = usg.UsergroupName
}).ToList();
ViewData["UsergroupID"] = UsergroupID;
return View("UserEdit", new UserAdminEditViewModel { User = u, Usergroups = _ug.GetUsergroups() });
And in my view I have:
<%= Html.ListBox("UsergroupID", (IEnumerable<SelectListItem>)ViewData["UsergroupID"]) %>
What's the reason for it not making the 3 items that have selected = true selected in the selectlist?
/M
looks like another bug in MVC to me ... you can refer to this link explaining part of the issue Link