我如何使用和保存视图模型

时间:2012-07-23 14:31:13

标签: c# asp.net-mvc-3

查看模型:

namespace AESSmart.ViewModels
{
    public class HomeIndexViewModel
    {
        public power_weatherstationhistory WeatherStationHistory {get;set;}
        public DateTime startingDate {get;set;}
        public DateTime endingDate {get;set;}
        public DateTime utcStartingDate {get;set;}
        public DateTime utcEndingDate {get;set;}
        public double LifeTimeGeneration {get;set;}
        public double CO2Offset {get;set;}
        public double GallonsOfGasolineOffset {get;set;}
        public double BarrelsOfOilOffset {get;set;}
        public string Message {get;set;}
    }
}

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AESSmart.Models;
using AESSmart.ViewModels;

namespace AESSmart.Controllers
{
    public class HomeController : Controller
    {
        private readonly AESSmartEntities db = new AESSmartEntities();

        public ActionResult Index()
        {
            HomeIndexViewModel IndexViewModel = new HomeIndexViewModel();

        if (Convert.ToString(IndexViewModel.startingDate) == 
                                      "1/1/0001 12:00:00 AM" ||
            Convert.ToString(IndexViewModel.endingDate) == 
                                      "1/1/0001 12:00:00 AM") 
            {
                IndexViewModel.startingDate = 
                     new DateTime(DateTime.Now.Year, 
                                  DateTime.Now.Month, 
                                  DateTime.Now.Day, 
                                  0, 
                                  0, 
                                  0);
                IndexViewModel.endingDate = 
                     new DateTime(DateTime.Now.Year, 
                                  DateTime.Now.Month, 
                                  DateTime.Now.Day, 
                                  23,
                                  59, 
                                  59);
            }

            // There is a bunch of code here to gather all of the
            // data need and modify the values of IndexViewModel 

            return View(IndexViewModel);
        }
    }
}

我的索引页面使用以下内容:@model AESSmart.ViewModels.HomeIndexViewModel然后我使用@Model.Something呈现视图中的每个部分。

视图中使用的数据只需要显示。用户可以修改的唯一数据是startingDateEndingDate。一旦他们修改了其中任何一个,我希望Index的{​​{1}} ActionResult使用这些新日期来提取正确的信息。现在它只是默认回到同一个日期(那个日期是今天的日期)。我在这里做错了什么?

此外,HomeController Index会收集天气信息。我希望收集的任何信息实际保存到数据库中。如何保存ActionResult中包含的信息?

以下是用户看到的内容示例:

enter image description here

2 个答案:

答案 0 :(得分:2)

我将大部分代码移到了View Model。为了保存更改,我将WeatherStationHistory添加到数据库上下文并保存了更改。现在一切都按预期工作。以下是我的代码现在的样子:

查看型号:

namespace AESSmart.ViewModels
{
  public class HomeIndexViewModel
  {
    public power_weatherstationhistory WeatherStationHistory {get;set;}
    public DateTime startingDate {get;set;}
    public DateTime endingDate {get;set;}
    public DateTime utcStartingDate {get;set;}
    public DateTime utcEndingDate {get;set;}
    public double LifeTimeGeneration {get;set;}
    public double CO2Offset {get;set;}
    public double GallonsOfGasolineOffset {get;set;}
    public double BarrelsOfOilOffset {get;set;}
    public string Message {get;set;}

    public void setUTCDatesTimes()
    {
      //Contains code to convert dates to the UTC equivalent 
    }

    public void setOffsetsAndPowerGenerated()
    {
      /*
       * CONTAINS A BUNCH OF CODE TO GATHER THE GENERATED POWER READINGS
       * FOR THE SPECIFIED DATETIME AND STORES RESULT IN LifeTimeGeneration.  
       * ALSO, PERFORMS CALCULATIONS TO GET AND STORE VALUES FOR CO2Offset, 
       * GallonsOfGasolineOffset, AND BarrelsOfOilOffset
       */
    }

    public void saveWeather()
    {
      AESSmartEntities db = new AESSmartEntities();
      db.PowerWeatherStationHistorys.Add(WeatherStationHistory);
      db.SaveChanges();
    }

    public void setWeather()
    {
      AESSmartEntities db = new AESSmartEntities();
      DateTime tempDate = (DateTime.UtcNow).AddMinutes(-5);

      var myQuery = (from s in db.PowerWeatherStationHistorys
                     where s.recordTime >= tempDate
                     orderby s.recordTime descending
                     select s).Take(1);

      if(myQuery.Count() > 0) 
      {
        /*
         * IF A WEATHER RECORD EXISTS IN THE THE DATABASE NO OLDER 
         * THAN 5 MINUTES THEN USE THAT INFORMATION
         */
      }
      else
      {
        /*
         * IF A RECORD DOES NOT EXIST IN THE THE DATABASE NO OLDER 
         * THAN 5 MINUTES THEN GET WEATHER INFORMATION FROM WUNDERGRAOUND API 
         * THEN SAVE IN DATABASE
         */

        saveWeather();
      }
    }
  }
}

<强>控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AESSmart.ViewModels;

namespace AESSmart.Controllers
{
  public class HomeController : Controller
  {
    public ActionResult Index()
    {
      HomeIndexViewModel IndexViewModel = new HomeIndexViewModel();

      IndexViewModel.startingDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
      IndexViewModel.endingDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
      IndexViewModel.setUTCDatesTimes();
      IndexViewModel.setWeather();
      IndexViewModel.setOffsetsAndPowerGenerated();
      IndexViewModel.Message = "Welcome to the Amptech Energy Systems Solar PV Monitoring System";

      return View(IndexViewModel);
    }

    [HttpPost]
    public ActionResult Index(HomeIndexViewModel IndexViewModel)
    {
      if (Convert.ToString(IndexViewModel.startingDate) == "1/1/0001 12:00:00 AM" || 
          Convert.ToString(IndexViewModel.endingDate) == "1/1/0001 12:00:00 AM")  
      {
        return RedirectToAction("Index");
      }

      IndexViewModel.setUTCDatesTimes();
      IndexViewModel.setWeather();
      IndexViewModel.setOffsetsAndPowerGenerated();
      IndexViewModel.Message = "Welcome to the Solar PV Monitoring System";

      return View(IndexViewModel);
    }     
  }
}

答案 1 :(得分:1)

您是否尝试为索引添加[HTTPPost]方法?

[HttpPost]
public ActionResult Index(HomeIndexViewModel viewModel) 
        { 

    if (Convert.ToString(viewModel.startingDate) == 
                             "1/1/0001 12:00:00 AM" || 
        Convert.ToString(viewModel.endingDate) == 
                             "1/1/0001 12:00:00 AM")  
        { 
            viewModel.startingDate = new DateTime(DateTime.Now.Year, 
                                                  DateTime.Now.Month, 
                                                  DateTime.Now.Day,  
                                                  0,  
                                                  0,  
                                                  0); 
            viewModel.endingDate = new DateTime(DateTime.Now.Year,  
                                                DateTime.Now.Month,  
                                                DateTime.Now.Day,  
                                                23,  
                                                59,  
                                                59); 
        } 

        // There is a bunch of code here to gather all of the 
        // data need and modify the values of IndexViewModel  

        return View(viewModel); 
    }