var categoryModel = AfvClassifiedsDB.Categories.Include("Listings")
.Single(c => c.Title == categoryName);
var viewModel = new ClassifiedsBrowseViewModel
{
Category = categoryModel,
Listings = categoryModel.Listings.OrderBy(c => c.Price).ToList(),
DateListed =
};
我正在从数据库中检索一些结果,然后在ViewModel中声明它们。
我想给DateListed(视图模型的一部分)一个值。此值是列表的一部分。但是,我想要这个值是特定的日期格式:“。ToString(”MMMM dd,yyyy“);”
为什么我无法从列表中获取值,有点卡住了。
非常感谢, Ĵ
编辑添加完整的ActionMethod:
public ActionResult ViewCategory(string categoryName, string searchCriteria = "Price")
{
// Retrieve Category and its associated Listings from the database
var categoryModel = AfvClassifiedsDB.Categories.Include("Listings")
.Single(c => c.Title == categoryName);
var viewModel = new ClassifiedsBrowseViewModel();
viewModel.Category = categoryModel;
viewModel.Listings = categoryModel.Listings.OrderBy(c => c.Price).ToList();
viewModel.DateListed = viewModel.Listings.First().DateListed.ToString("MMMM dd, yyyy");
switch(searchCriteria)
{
case "Title":
viewModel.Listings = categoryModel.Listings.OrderBy(c => c.Title).ToList();
break;
case "Price":
viewModel.Listings = categoryModel.Listings.OrderBy(c => c.Price).ToList();
break;
case "FuelType":
viewModel.Listings = categoryModel.Listings.OrderBy(c => c.FuelType).ToList();
break;
case "Transmission":
viewModel.Listings = categoryModel.Listings.OrderBy(c => c.Transmission).ToList();
break;
default:
viewModel.Listings = categoryModel.Listings.OrderBy(c => c.DateListed).ToList();
break;
}
return View(viewModel);
}
答案 0 :(得分:0)
答案 1 :(得分:0)
不确定您的数据是什么样的,但不应该这样做吗?
DateListed = categoryModel.DateListed.ToString("MMMM dd, yyyy");
答案 2 :(得分:0)
您不能在此处使用属性初始值设定项。逐步分配值:
var viewModel = new ClassifiedsBrowseViewModel();
viewModel.Category = categoryModel;
viewModel.Listings = categoryModel.Listings.OrderBy(c => c.Price).ToList();
viewModel.DateListed = viewModel.Listings.Select(item=>item.ToString("MMMM dd, yyyy")).ToList();
一个简单的解释:
class Person
{
public int ID { get;set; }
public string Name { get;set; }
}
var p = new Person { ID=1, Name="test1" }; //ok
var another = new Person
{
ID = 2,
Name = "test"+ID //compile error
};
var again = new Person();
again.ID = 3;
again.Name = "test"+again.ID; //of course it's correct
答案 3 :(得分:0)
假设您在列表
中的对象上列出了日期属性DateListed = categoryModel.Listings.First().DateListed.ToString("MMMM dd, yyyy")
答案 4 :(得分:0)
我认为您的问题是调用Single
而不是First
我会使用这样的代码:
var categoryModel = AfvClassifiedsDB.Categories.Include("Listings")
.First(c => c.Title == categoryName);
var viewModel = new ClassifiedsBrowseViewModel
{
Category = categoryModel,
Listings = categoryModel.Listings.OrderBy(c => c.Price).ToList(),
DateListed = categoryModel.Listings.DateListed.ToString("("MMMM dd, yyyy")
};
单个返回长度为1的列表,并且First返回列表中的第一个对象。