【发布时间】:2011-04-04 09:34:57
【问题描述】:
亲爱的,我有一个简单的问题,我找不到答案。我创建了一个列表视图,在 url 中传递不同的数据操作值。我当前的网址类似于:http://localhost/App/Product/List?categoryId=2&countryId=us。
我有来自不同类别和国家/地区的产品,有谁知道我必须传递哪个值才能显示来自所有国家/地区的产品或来自所有类别的产品而不是特定的产品?类似 /List?categoryId=""&countryId=""
一位同事告诉我执行以下操作: 我认为您应该使用可为空的整数( int? )作为 categoryid 参数的类型:
public ActionResult List(int? categoryid, int? page, string countryId)
{
var products = null;
if (categoryid.HasValue && !string.IsNullOrEmpty(countryId)) {
products = ProductRepository.FindCategoryProducts(categoryid, countryId).AsPagination(page.GetValueOrDefault(1), 20);
} else if (categoryid.HasValue == false && string.IsNullOrEmpty(countryId)) {
products = ProductRepository.GetAllProducts();
} else {
/// check the other cases here...
return View(products);
}
}
但似乎如果我只有两个参数是可能的,但如果有很多参数,我将有很多 if - else if 来显示所有可能性。
这是过滤数据的唯一方法还是存在任何其他选项?
任何帮助将不胜感激。 brgds
更新!!:
嗨,杰森,非常感谢。我有以下控制器:
public ActionResult List(int categoryid, int? page, string countryId)
{
var products = ProductRepository.FindCategoryProducts(categoryid, countryId).AsPagination(page.GetValueOrDefault(1), 20);
return View(products);
}
产品存储库:
public IQueryable<Product> FindCategoryProducts(int categoryId, string countryId)
{
return from product in db.product
where product.CategoryId == categoryId
&& product.CountryId == countryId
orderby product.CreatedOn
select product;
}
然后我可以通过 URL Product/list?categoryId=2&countryId=us 。但是,如果我想检索所有产品,无论哪个国家/地区喜欢使用可为空的字符串,我都会收到错误消息。 这就是为什么这位同事建议我创建 - if /elseif 语句 - 考虑到所有参数的可能性,但如果作为示例我有 8 个参数,这似乎是一个很长的语句。
谢谢!
【问题讨论】:
-
取决于您如何设置数据库。如果您有产品 X,您是否有针对每个国家/地区的单独产品 ID?还是您有一个产品 ID,然后单独存储每个国家/地区的信息?没有更多细节,没有人可以为你回答这个问题。这就像说你从一本书中得到一个页面,想知道上面的单词是什么,但不知道这本书的标题或页码是什么。
-
我发布了更多信息,如下所示,我想知道如何使用表单创建列表视图来操作具有多个参数的数据。就像电子商务网站根据类别、最高最低价格、属性等进行列表视图一样。brgds!
标签: c# asp.net sql asp.net-mvc-3