Reputation: 2642
I have to method in model of my asp.net mvc project.
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;
}
I want to combine these 2 method, it is work the same each other, except the parameter of the function.
Any ideas please.
Upvotes: 1
Views: 775
Reputation: 127
You can try like this:
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;
}
Upvotes: 2
Reputation: 57573
You could try:
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;
}
Upvotes: 2
Reputation: 2797
Default parameters are available from 4.0 version. Also, read this article from MS http://blogs.msdn.com/b/csharpfaq/archive/2004/03/07/85556.aspx
Upvotes: 1
Reputation: 498904
Use an optional argument:
public JsonResult GetProductByCatList(string depID, string catID = "0")
Upvotes: 3
Reputation: 62248
public JsonResult GetProductByCatList(string depID, string catID = "-1")
{
//common shared code
return jr;
}
Assuming that default value is -1
for catID
Upvotes: 2