Null JSON GET ASP.NET MVC - c#

Hi I have two controller methods. I am passing two parameters from the 1st method to the 2nd. The values inserted to database are correct and not NULL. However when there are displayed back on the webpage in the return Json line, they come out as null and im not sure as to why? Here are the controller methods:
[HttpPost]
public void CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
CalculateAndSaveToDB(CalculateModel.BMICalc.ToString(), CalculateModel.BMIMeaning.ToString());
}
public JsonResult CalculateAndSaveToDB(string o, string t)
{
var data = new
{
CalculatedBMI = o,
CalculatedBMIMeaning = t
};
return Json(data, JsonRequestBehavior.AllowGet);
}
Update
BMICalculationsModel:
public partial class BMICalculation
{
public string Id { get; set; }
public System.DateTime Date { get; set; }
public Nullable<double> BMICalc { get; set; }
[Required]
public double Height { get; set; }
[Required]
public double Weight { get; set; }
public int BMICalculationID { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
public string BMIMeaning { get; set; }
public double CalculateMyBMI(double KG, double Height)
{
return KG / (Height * Height);
}
public string BMIInfo(double? BMI)
{
string BMIInfo = "";
if (BMI <= 18.5)
{
BMIInfo = "Underweight";
}
else if (BMI > 18.5 && BMI < 25)
{
BMIInfo = "Average";
}
else if (BMI > 25)
{
BMIInfo = "Overweight";
}
return BMIInfo;
}
}

You need to make your first method return JsonResult and not void. The second CalculateAndSaveToDB returns a JsonResult which never gets used.
I would definitely not call that second method CalculateAndSaveToDB as it doesn't save anything to the DB. Maybe GenerateJsonCalc would be more suitable or maybe no method at all:
[HttpPost]
public JsonResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
return CalculateAndSaveToDB(CalculateModel.BMICalc.ToString(), CalculateModel.BMIMeaning.ToString());
I would go for something like:
return Json(new
{
CalculatedBMI = CalculateModel.BMICalc.ToString(),
CalculatedBMIMeaning = CalculateModel.BMIMeaning.ToString()
}, JsonRequestBehavior.AllowGet);

Change your return type of your POST method and its last line to this:
public ActionResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
//stuff
return RedirectToAction("CalculateAndSaveToDB", new { o = CalculateModel.BMICalc.ToString(), t = CalculateModel.BMIMeaning.ToString());
}

try return a dynamic object
public dynamic CalculateAndSaveToDB(BMICalculation CalculateModel)
{
...
return CalculateAndSaveToDB(CalculateModel.BMICalc.ToString(), CalculateModel.BMIMeaning.ToString());
}
public dynamic CalculateAndSaveToDB(string o, string t)
{
dynamic data = new new ExpandoObject();
data.CalculatedBMI = o;
data.CalculatedBMIMeaning = t;
return data ;
}

Related

Get Newly Created DB ID to pass to Quote Method

EDIT: I have the Quote working on EDIT, but it's not working on Create. I've adjusted my method from my original post. So my issue is I cannot figure out to pass the ID of a newly created record to the quote method.
Student here!
Creating an MVC app and I cannot figure out I'm missing. I thought I had it working and then I moved on, but when I went back to test, I realized it wasn't working and am getting a bunch of errors. I know the reason is because the values I think I'm passing aren't actually being passed.
I have the two scenarios, Create and Edit and when the DB entry is created it should redirect to my quote method, but that is where I'm getting errors. I can't figure out how to pass the values that were just created to the quote method. Any suggestions as to what I'm missing would be appreciated!
This is my controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CarInsurance.Models;
using CarInsurance.View_Models;
namespace CarInsurance.Controllers
{
public class InsureeController : Controller
{
private InsuranceEntities db = new InsuranceEntities();
// GET: Insuree/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Insuree insuree = db.Insurees.Find(id);
if (insuree == null)
{
return HttpNotFound();
}
return View(insuree);
}
// GET: Insuree/Create
public ActionResult Create()
{
return View();
}
// POST: Insuree/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "FirstName,LastName,EmailAddress,DateOfBirth,CarYear,CarMake,CarModel,DUI,SpeedingTickets,CoverageType")] Insuree insuree)
{
if (ModelState.IsValid)
{
db.Insurees.Add(insuree);
db.SaveChanges();
}
return RedirectToAction("Quote", insuree);
}
// GET: Insuree/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Insuree insuree = db.Insurees.Find(id);
if (insuree == null)
{
return HttpNotFound();
}
return View(insuree);
}
// POST: Insuree/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName,LastName,EmailAddress,DateOfBirth,CarYear,CarMake,CarModel,DUI,SpeedingTickets,CoverageType")] Insuree insuree)
{
if (ModelState.IsValid)
{
db.Entry(insuree).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Quote", insuree);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
// GET: Quote
public ActionResult Quote(int? id)
{
Insuree insuree = db.Insurees.Find(id);
Quote quote = new Quote();
quote.FirstName = insuree.FirstName;
quote.LastName = insuree.LastName;
quote.EmailAddress = insuree.EmailAddress;
quote.DateOfBirth = insuree.DateOfBirth;
quote.CarYear = insuree.CarYear;
quote.CarMake = insuree.CarMake;
quote.CarModel = insuree.CarModel.ToLower();
quote.DUI = Convert.ToBoolean(insuree.DUI);
quote.SpeedingTickets = insuree.SpeedingTickets;
quote.CoverageType = Convert.ToBoolean(insuree.CoverageType);
var age = DateTime.Now.Year - insuree.DateOfBirth.Year;
decimal totalQuote = 50;
// Age Constraints
if (age <= 18)
{
totalQuote += 100;
quote.quoteAge = 100;
}
if (age >= 19 && age <= 25)
{
totalQuote += 50;
quote.quoteAge = 50;
}
if (age > 25)
{
totalQuote += 25;
quote.quoteAge = 25;
}
// Car Constraints
if (quote.CarYear < 2000 || quote.CarYear > 2015)
{
totalQuote += 25;
quote.quoteCar = 25;
}
if (quote.CarMake == "porsche")
{
totalQuote += 25;
quote.quoteCar += 25;
}
if (quote.CarModel == "911 carrera")
{
totalQuote += 25;
quote.quoteCar += 25;
}
// Driving History Constraints
if (quote.SpeedingTickets > 0)
{
totalQuote += quote.SpeedingTickets * 10;
quote.quoteTickets = quote.SpeedingTickets * 10;
}
if (quote.DUI)
{
totalQuote *= Convert.ToDecimal(1.25);
quote.quoteDUI = totalQuote * Convert.ToDecimal(.25);
}
// Coverage Requested
if (quote.CoverageType)
{
totalQuote *= Convert.ToDecimal(1.50);
}
ViewBag.Quote = Math.Round(totalQuote, 2);
return View(quote);
}
}
}
And my quote class if needed:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CarInsurance.View_Models
{
public class Quote
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public DateTime DateOfBirth { get; set; }
public int CarYear { get; set; }
public string CarMake { get; set; }
public string CarModel { get; set; }
public bool DUI { get; set; }
public int SpeedingTickets { get; set; }
public bool CoverageType { get; set; }
public decimal quoteAge { get; set; }
public decimal quoteCar { get; set; }
public decimal quoteTickets { get; set; }
public decimal quoteDUI { get; set; }
}
}

Error CS0161 'RateController.GetRateById(long)': not all code paths return a value

I have an error
Severity Code Description Project File Line Suppression State Error CS0161 'RateController.GetRateById(long)': not all code paths return a value shenoywebapi D:\shenoystudio\shenoywebapi\Controllers\RateController.cs 192 Active
[Route("api/rate/getrate/{id}")]
public Rate GetRateById(long id)
{
var result = new Rate();
var dsRate = SqlHelper.ExecuteDataset(AppDatabaseConnection, CommandType.StoredProcedure, 0, "GetRateById", new SqlParameter("#Id", id));
if (dsRate.Tables[0].Rows.Count > 0)
{
DataRow row = dsRate.Tables[0].Rows[0];
result = new Rate
{
Id = Convert.ToInt64(row[0]),
wefDate = Convert.ToDateTime(row[1]),
//ProductRates =new List<ProductRate>() { new ProductRate() { Rate = Convert.ToInt64(row[2])} }
};
}
var ProductRatesList = new List<ProductRate>();
var dsRateDetails = SqlHelper.ExecuteDataset(AppDatabaseConnection, CommandType.StoredProcedure, 0, "GetRateDetailsById", new SqlParameter("#RateId", id));
if (dsRateDetails.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dsRateDetails.Tables[0].Rows)
{
ProductRatesList.Add(new ProductRate
{
Rate = Convert.ToDecimal(row[0])
});
}
result.ProductRates = ProductRatesList;
return result;
}
}
This is my rate model
{
public class Rate
{
public long Id { get; set; }
public DateTime wefDate { get; set; }
public IList<ProductRate> ProductRates { get; set; }
}
}
This is my ProductRate Model
namespace shenoywebapi.Models
{
public class ProductRate
{
public long Id { get; set; }
public string SerialNumber { get; set; }
public long ProductId { get; set; }
public string ProductName { get; set; }
public string Unit { get; set; }
public decimal Rate { get; set; }
}
}
Only on this part you have a return statement:
if (dsRateDetails.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in dsRateDetails.Tables[0].Rows)
{
ProductRatesList.Add(new ProductRate
{
Rate = Convert.ToDecimal(row[0])
});
}
result.ProductRates = ProductRatesList;
return result;
}
if the code goes not to this if statement, there is no return statement
if (dsRateDetails.Tables[0].Rows.Count > 0)
you should add this before the last curly brace of the method:
return result;

How to check if duplicate data is present in the database using asp.net mvc

I want to show a message saying that the JourneyID already exists in the database.
The model is :
using System.Web.Mvc;
namespace Project_Final.Models
{
using System;
public partial class sp_FMS_Group6_Module3_ViewBonusMilesRequesttt_Result
{
public int RequestID { get; set; }
public Nullable<long> CustomerID { get; set; }
[Remote("Check", "Home", ErrorMessage = "Bonus Miles Request has already been sent!")]
public Nullable<int> JourneyID { get; set; }
public Nullable<System.DateTime> RequestDate { get; set; }
public string Status { get; set; }
}
}
The following are the actions in my controller :
[HttpPost]
public ActionResult Index(string Create)
{
FMS_Group6_Module3_BonusMilesRequestt objProd = new FMS_Group6_Module3_BonusMilesRequestt();
objProd.CustomerID = int.Parse(Request.Form["CustomerID"].ToString());
objProd.JourneyID = int.Parse(Request.Form["JourneyID"].ToString());
objProd.RequestDate = DateTime.Parse(Request.Form["RequestDate"].ToString());
objProd.Status = "Pending";
objDB.FMS_Group6_Module3_BonusMilesRequestt.Add(objProd);
int i = objDB.SaveChanges();
if (i > 0)
ViewBag.Message = "Product details saved successfully";
return Content("<script language='javascript' type='text/javascript'>alert('Your Bonus Miles Request has been successfully sent!');window.location='/Home/GetID'</script>");
//return Redirect("GetID");
}
public ActionResult Check(string Crreate)
{
FMS_Group6_Module3_BonusMilesRequestt objProd = new FMS_Group6_Module3_BonusMilesRequestt();
bool ifJourneyIDExist = false;
try
{
ifJourneyIDExist = Crreate.Equals(objProd.JourneyID) ? true : false;
return Json(!ifJourneyIDExist, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
Any kind of help would be greatly appreciated. Thanks.
Before you insert, you can check in the DB, if the JourneyID is exists.
if (objDB.FMS_Group6_Module3_BonusMilesRequestt.Any(x => x.JourneyID == objProd.JourneyID))
{
// Exists
}
LINQ query to make sure all values (ex enumerable) are not duplicated
var noDuplicationVariable = enumerableValues.GroupBy(a => a.Key).All(b => b.Count() == 1);
use it as an assertion condition before your function

foreach statement error GetEnumerator

I am attempting to build a blog based on a tutorial from VS 2010, and using VS 2013 I am getting errors. Any help would be appreciated. My Foreach statement will not execute.. I am getting an error stating Foreach statement cannot operate on variables of type 'blog.Models.Tag' because blog.Models.Tag does not contain a public definition for Get Enumerator...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using blog.Models;
using System.Text;
namespace blog.Controllers
{
public class PostsController : Controller
{
private BlogModel model = new BlogModel();
private const int PostsPerPage = 4;
public ActionResult Index(int? id)
{
int pageNumber = id ?? 0;
IEnumerable<Post> posts =
(from post in model.Posts
where post.DateTime < DateTime.Now
orderby post.DateTime descending
select post).Skip(pageNumber * PostsPerPage).Take(PostsPerPage + 1);
ViewBag.IsPreviousLinkVisible = pageNumber > 0;
ViewBag.IsNextLinkVisible = posts.Count() > PostsPerPage;
ViewBag.PageNumber = pageNumber;
ViewBag.IsAdmin = IsAdmin;
return View(posts.Take(PostsPerPage));
}
public ActionResult Details(int id)
{
Post post = GetPost(id);
ViewBag.IsAdmin = IsAdmin;
return View(post);
}
[ValidateInput(false)]
public ActionResult Comment(int id, string name, string email, string body)
{
Post post = GetPost(id);
Comment comment = new Comment();
comment.Post = post;
comment.Time = DateTime.Now;
comment.Name = name;
comment.Email = email;
comment.Body = body;
model.Comments.Add(comment);
model.SaveChanges();
return RedirectToAction("Details", new { id = id });
}
public ActionResult Tags(string id)
{
Tag Tag = (dynamic)GetTag(id);
ViewBag.IsAdmin = IsAdmin;
return View("Index", Tag.Posts);
}
[ValidateInput(false)]
public ActionResult Update(int? id, string title, string body, DateTime dateTime, string tags)
{
if(!IsAdmin)
{
return RedirectToAction("Index");
}
Post post = GetPost(id);
post.Title = title;
post.Body = body;
post.DateTime = dateTime;
post.Tags.Clear();
tags = tags ?? string.Empty;
string[] tagNames = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string tagName in tagNames)
{
post.Tags.Add(GetTag(tagName));
}
if(!id.HasValue)
{
model.Posts.Add(post);
}
model.SaveChanges();
return RedirectToAction("Details", new { id = post.Id });
}
public ActionResult Edit(int? id)
{
Post post = GetPost(id);
StringBuilder tagList = new StringBuilder();
foreach(Tag tag in post.Tags)
{
tagList.AppendFormat("{0} ", tag.Name);
}
ViewBag.Tags = tagList.ToString();
return View(post);
}
private object GetTag(string tagName)
{
return model.Tags.Where(x => x.Name == tagName).FirstOrDefault() ?? new Tag() {Name = tagName};
}
private Post GetPost(int? id)
{
return id.HasValue ? model.Posts.Where(x => x.Id == id).First() : new Post() { Id = -1 };
}
//TODO: Fix this later
public bool IsAdmin { get { return true; } }
}
}
Here is my Tag.cs
namespace blog.Models
{
using System;
using System.Collections.Generic;
public partial class Tag
{
public Tag()
{
this.Posts = new HashSet<Post>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Post> Posts { get; set; }
internal void Clear()
{
//throw new NotImplementedException();
}
internal void Add(object p)
{
//throw new NotImplementedException();
}
}
}
Here is my Posts.cs
namespace blog.Models
{
using System;
using System.Collections.Generic;
public partial class Post
{
public Post()
{
this.Comments = new HashSet<Comment>();
}
public int Id { get; set; }
public string Title { get; set; }
public System.DateTime DateTime { get; set; }
public string Body { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual Tag Tags { get; set; }
}
}
Foreach can only be done on a collection implementing the GetEnumerator, because it uses this function to get the "next" item to foreach on. Apparently this function is not present.

c# property doesn't get filled up

I'm trying to set a property Klimatogram.Locatie in a controller class like this:
public ActionResult SelectKlimatorgramVanLocatie(LocatieKlimatogramViewModel model)
{
Locatie selectedLocatie = (Locatie)Session["GevondenLocatie"];
Klimatogram klimatogram = new Klimatogram(selectedLocatie);
TempData["kilmatogram"] = klimatogram;
return RedirectToAction("Index", "Vragen");
}
So if I debug I can see that klimatogram.Locatie is being set by selectedLocatie.
EDIT :
Now klimatogram.Locatie gets filled up. But when i look at the values from Klimatogram they are all 0.
Here is an example in the class Klimatogram:
public class Klimatogram
{
public Klimatogram(Locatie selectedLocatie)
{
Locatie =selectedLocatie;
}
public Locatie Locatie { get; set; }
public int Id { get; set; }
private double warmsteMaand;
private double aantalDrogeMaanden;
private double gemJaarTemp;
private double gemJaarNeerslag;
private double hoeveelNeerslagWinter;
private double hoeveelNeerslagZomer;
private double koudsteMaand;
public int klimaId { get; set; }
public double TempWarmsteMaand
{
get { return warmsteMaand; }
set
{
value = Locatie.TemperatuurPerMaand[0];
for (int i = 1; i < 12; i++)
{
if (Locatie.TemperatuurPerMaand[i] > value)
{
value = Locatie.TemperatuurPerMaand[i];
}
}
warmsteMaand = value;
}
}
So this method doesn't get any value from my Locatie. When i debug it says it is 0 which is wrong.
this is my vragenController:
public ActionResult Index()
{
var klimatogram = (Klimatogram)TempData["kilmatogram"];
VragenViewModel vragenViewModel = new VragenViewModel(klimatogram);
return View("VragenControl",vragenViewModel);
}
This is the viewmodel:
public class VragenViewModel
{
// public SelectList Maanden { get; set; }
public VragenViewModel()
{
}
public VragenViewModel(Klimatogram klima)
{
warm = klima.TempWarmsteMaand;
koud = klima.TempKoudsteMaand;
droge = klima.AantalDrogeMaanden;
winterneerslag = klima.HoeveelheidNeerslagWinter;
zomerneerslag = klima.HoeveelheidNeerslagZomer;
}
public double zomerneerslag
{ get; set; }
public double winterneerslag { get; set; }
public double droge { get; set; }
public double koud { get; set; }
public double warm { get; set; }
}
maybe just
public ActionResult SelectKlimatorgramVanLocatie(LocatieKlimatogramViewModel model)
{
Locatie selectedLocatie = (Locatie)Session["GevondenLocatie"];
Klimatogram klimatogram = new Klimatogram();
klimatogram.Locatie = selectedLocatie;
return Index(klimatogram);
}
The third argument of RedirectToAction is routeValues, not passing a model like you do with View.
You can use the TempData variable to pass data through as per this answer:
public ActionResult SelectKlimatorgramVanLocatie(LocatieKlimatogramViewModel model)
{
Locatie selectedLocatie = (Locatie)Session["GevondenLocatie"];
Klimatogram klimatogram = new Klimatogram();
klimatogram.Locatie = selectedLocatie;
TempData["kilmatogram"] = kilmatogram;
return RedirectToAction("Index", "Vragen");
}
// ...
public ActionResult Index()
{
var kilmatogram = (Kilmatogram)TempData["kilmatogram"];
// ...
}

Categories

Resources