如果用户忽略该表单,并直接转到该网页,我希望今天的日期为默认值。
但我觉得复制粘贴这两行之间的所有代码行是不好的代码,而唯一的改变是日期。
如何清理此代码?
第一个结果()我所做的就是自己设置objdate1.DateStart 在[HttpPost]中,我从表单中获取objdate1.DateStart。
public ActionResult Results()
{
Date1 objdate1 = new Date1();
objdate1.DateStart = DateTime.Now;
var DataContext = new BalanceDataContext();
DateTime earliestDate = objdate1.DateStart.Value.AddMonths(-13);
//Tons of Code omitted Here ---------------------------
ViewBag.Metric = 1;
ViewBag.Message = objdate1.DateStart.Value.ToString("yyyy-MMMM-dd");
ViewBag.Title2 = "% of Electric Estimated";
ViewBag.Descript = "Percentage of estimated electric bills per Month.";
return View(new QueryView { Date2 = totalbills, Date1 = totalEstimated });
}
[HttpPost]
public ActionResult Results(Date1 objdate1)
{
var DataContext = new BalanceDataContext();
DateTime earliestDate = objdate1.DateStart.Value.AddMonths(-13);
//Exact same Code omitted Here ---------------------------
ViewBag.Metric = 1;
ViewBag.Message = objdate1.DateStart.Value.ToString("yyyy-MMMM-dd");
ViewBag.Title2 = "% of Electric Estimated";
ViewBag.Descript = "Percentage of estimated electric bills per Month.";
return View(new QueryView { Date2 = totalbills, Date1 = totalEstimated });
}
答案 0 :(得分:1)
使参数可为空并删除无参数方法。
[HttpPost]
public ActionResult Results(Date1? objdate1)
{
var DataContext = new BalanceDataContext();
if (!objdate1.HasValue){
objdate1 = new Date1();
objdate1.DateStart = DateTime.Now;
}
DateTime earliestDate = objdate1.DateStart.Value.AddMonths(-13);
//Exact same Code omitted Here ---------------------------
ViewBag.Metric = 1;
ViewBag.Message = objdate1.DateStart.Value.ToString("yyyy-MMMM-dd");
ViewBag.Title2 = "% of Electric Estimated";
ViewBag.Descript = "Percentage of estimated electric bills per Month.";
return View(new QueryView { Date2 = totalbills, Date1 = totalEstimated });
}
答案 1 :(得分:0)
来自C#Freenode的用户RandomStrangler给了我答案:
"在一个单独的类中有逻辑,只需从两个动作中调用它。"
所以我创建了一个名为Query的单独的类,并执行此操作:
public ActionResult Results()
{
Date1 objdate1 = new Date1();
objdate1.DateStart = DateTime.Now;
Querys estview = new Querys();
ViewBag.Metric = 1;
ViewBag.Message = objdate1.DateStart.Value.ToString("yyyy-MMMM-dd");
ViewBag.Title2 = "% of Electric Estimated";
ViewBag.Descript = "Percentage of estimated electric bills per Month.";
return View(estview.estimatedbills(objdate1.DateStart));
}
[HttpPost]
public ActionResult Results(Date1 objdate1)
{
Querys estview = new Querys();
ViewBag.Metric = 1;
ViewBag.Message = objdate1.DateStart.Value.ToString("yyyy-MMMM-dd");
ViewBag.Title2 = "% of Electric Estimated";
ViewBag.Descript = "Percentage of estimated electric bills per Month.";
return View(estview.estimatedbills(objdate1.DateStart));
}
很多整洁。