1

我必须在我的 asp.net mvc 项目的模型中使用方法。

public JsonResult GetProductsByDepList(string depID)
{
  JsonResult jr = new JsonResult();
  var _product = from a in DataContext.GetProductsByDep(Convert.ToInt32(depID))
  select new { ID = a.ID, ProName = a.Name };
  jr.Data = _product.ToList();
  jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
  return jr;
 }


 public JsonResult GetProductByCatList(string depID, string catID)
 {
   JsonResult jr = new JsonResult();
   var _product = from a in   
   DataContext.GetProductsByCat(Convert.ToInt32(depID),Convert.ToInt32(catID))
   select new { ID = a.ID, ProName = a.Name };
   jr.Data = _product.ToList();
   jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
   return jr;
 }

我想将这两种方法结合起来,除了函数的参数外,它们的工作原理相同。

请有任何想法。

4

5 回答 5

3

使用可选参数

public JsonResult GetProductByCatList(string depID, string catID = "0")
于 2012-04-10T09:33:16.607 回答
2
 public JsonResult GetProductByCatList(string depID, string catID = "-1")
 {
   //common shared code
   return jr;
 }

假设默认-1值为catID

于 2012-04-10T09:33:03.337 回答
2

你可以试试:

public JsonResult GetProductByCatList(string depID, string catID = null)
{
  JsonResult jr = new JsonResult();
  if (String.IsNullOrEmpty(catID))
  {
      var _product = from a in DataContext.GetProductsByDep(Convert.ToInt32(depID))  
      select new { ID = a.ID, ProName = a.Name };
      jr.Data = _product.ToList();      
  } else {
      var _product = from a in   
      DataContext.GetProductsByCat(Convert.ToInt32(depID),Convert.ToInt32(catID))
      select new { ID = a.ID, ProName = a.Name };
      jr.Data = _product.ToList();      
  }
  return jr;
}
于 2012-04-10T09:33:47.457 回答
2

你可以这样尝试:

   public JsonResult GetProductsByDepList(string depID)
   {
       return GetProductByCatList(depID, null);
   }

   public JsonResult GetProductByCatList(string depID, string catID)
   {
       JsonResult jr = new JsonResult();
       var _product = null;
       if (!string.IsNullOrEmpty(catID))
       {
           _product = from a in   
               DataContext.GetProductsByCat(Convert.ToInt32(depID),Convert.ToInt32(catID))
               select new { ID = a.ID, ProName = a.Name };
       }
       else
       {
           _product = from a in DataContext.GetProductsByDep(Convert.ToInt32(depID))
               select new { ID = a.ID, ProName = a.Name };
       } 

       jr.Data = _product.ToList();
       jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
       return jr;
   }
于 2012-04-10T09:51:05.617 回答
1

从 4.0 版本开始提供默认参数。另外,请阅读 MS http://blogs.msdn.com/b/csharpfaq/archive/2004/03/07/85556.aspx的这篇文章

于 2012-04-10T09:36:51.093 回答