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.
Use an optional argument :
public JsonResult GetProductByCatList(string depID, string catID = "0")
public JsonResult GetProductByCatList(string depID, string catID = "-1")
{
//common shared code
return jr;
}
Assuming that default value is -1
for catID
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;
}
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;
}
Default parameters are available from 4.0 version. Also, read this article from MShttp://blogs.msdn.com/b/csharpfaq/archive/2004/03/07/85556.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.