2012-04-10 86 views
1

我必須在我的asp.net mvc項目模型中使用方法。c#函數中的可選參數

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; 
} 

我想結合這兩種方法,除了函數的參數以外,它們是一樣的。

任何想法請。

+1

鑑於這兩種方法做不同的事情,你爲什麼要他們結合? – ChrisF 2012-04-10 09:32:53

回答

2
public JsonResult GetProductByCatList(string depID, string catID = "-1") 
{ 
    //common shared code 
    return jr; 
} 

假設默認值是-1catID

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; 
} 
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; 
    } 
+0

這有錯誤,你不能聲明'_product'兩次,並且你不能在if/else語句之後把'select'位自己關閉。您還需要頂層函數中的'return'。 – joshuahealy 2012-04-11 06:18:25

+0

但是否則這有潛力:) – joshuahealy 2012-04-11 06:18:49