Linger
Linger

Reputation: 15048

How do I work with and save viewmodels

view model:

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;}
    }
}

controller:

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);
        }
    }
}

My index page is uses the following: @model AESSmart.ViewModels.HomeIndexViewModel then I use @Model.Something to render each piece in the View.

There is a bunch of data used in the view that just needs to be displayed. The only pieces of data the user can modify are the startingDate and EndingDate. Once they modify either of those I want the Index ActionResult of the HomeController to use those new dates to pull the correct information. Right now it just defaults back to the same date (that date being whatever today's date is). What am I doing wrong here?

Also, the Index ActionResult gathers the weather information. I want whatever information that is gathered to actually be saved into the database. How do I save the information contained in WeatherStationHistory?

Here is a sample of what the user sees:

enter image description here

Upvotes: 3

Views: 387

Answers (2)

Linger
Linger

Reputation: 15048

I moved most of my code to the View Model. To save the changes I added WeatherStationHistory to the database context and saved the changes. Now everything works as desired. Here is the way my code looks now:

View Model:

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();
      }
    }
  }
}

Controller:

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);
    }     
  }
}

Upvotes: 2

Josh
Josh

Reputation: 10604

Have you tried adding an [HTTPPost] method for index?

[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); 
    } 

Upvotes: 1

Related Questions