如果用戶忽略表單並直接進入網頁,我希望今天的日期成爲默認值。如何清理此控制器?
但我覺得這是錯誤的代碼複製粘貼這兩個代碼之間的所有行,當唯一的變化是日期。
如何清理此代碼?
第一結果()我所做的是設置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 });
}
編寫一個採用'objdate1'並返回一個ActionResult的第三個函數? –
你究竟想要完成什麼?因爲我不確定爲什麼相應的get和post操作應該共享這麼多的代碼。您還應該介紹在屏幕上反映該數據的視圖模型。我不確定爲什麼你要在視圖模型中放置2個字段,然後在ViewBag中放置4個字段?爲什麼不把它們全部放在視圖模型中? – Fran
@Fran我只是喜歡Viewbag發送簡單的字符串到一個視圖,因爲它看起來更整潔,更容易找到我。個人喜好。另請參閱下面的結果。我把所有的代碼放在一個單獨的類中,我只是在需要時調用它。 –