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; }
}
}
Related
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
I have Book and each book can have multiple Chapter. Each of the Chapter has a single audio file. How can I update single row of chapter sub entity?
This is my model:
public class Book
{
public Book()
{
this.Chapters = new List<Chapter>();
}
[Key]
public Int64 ISBN { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BookID { get; set; }
public string bookName { get; set; }
public string bookAuthor { get; set; }
[DataType(DataType.Currency)]
public decimal bookPrice { get; set; }
public virtual ICollection<Chapter> Chapters { get; set; }
}
public class Chapter
{
public int ChapterId { get; set; }
public string chapterName { get; set; }
[ForeignKey("Book")]
public Int64 ISBN { get; set; }
public virtual Book Book { get; set; }
}
In Create ActionResult I add new Chapter by create new object from Chapter model and add it using book.Chapters.Add()
for (int i = 1; i < Request.Files.Count; i++)
{
var mfile = Request.Files[i];
if (mfile != null && mfile.ContentLength > 0)
{
var fileName = Path.GetFileNameWithoutExtension(mfile.FileName);
Chapter _bChapter = new Chapter()
{
chapterName = fileName,
chapterLink = BookDir + mfile.FileName
};
book.Chapters.Add(_bChapter);
mfile.SaveAs(Server.MapPath(_bChapter.chapterLink));
}
}
in Edit ActionResult I get new audio using HttpPostedFileBase
public ActionResult Edit(Book book, IEnumerable<HttpPostedFileBase> file)
{
if (ModelState.IsValid)
{
db.Entry(book).State = EntityState.Modified;
//do some File operation to save audio in server folder
db.SaveChanges();
return RedirectToAction("Index");
}
return View(book);
}
But I dont know how to save new uploaded audio to chapter sub entity
You can update Chapter, first find related chapter by using SingleOrDefault method, next edit chapterName property and call SaveChanges() method, like this:
using (var context = new YourDbContext())
{
var result = context.Chapter.SingleOrDefault(b => b.ISBN == book.ISBN);
if (result != null)
{
result.chapterName = #"/root/my/audios";
context.SaveChanges();
}
}
EDIT:
using (var context = new YourDbContext())
{
var result = context.Chapter.Where(b => b.ISBN == book.ISBN).ToList();
if (result.Any())
{
foreach(var chapter in result)
{
chapter.chapterName = #"/root/my/audios";
}
context.SaveChanges();
}
}
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.
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 ;
}
I stored some values into a model class using session variables and want to access them after the form submits. The values are stored in the ReportChooser Model and I would like to access the values in the View.
Report Controller
List<ReportEntryInfo> reiList = new List<ReportEntryInfo>();
foreach (string s in Request["ReportPeriodEntries"].ToString().Split(','))
{
string[] reportPeriodEntries = s.ToString().Split('_');
string reportPeriodID = reportPeriodEntries[0];
string entryID = reportPeriodEntries[1];
ReportEntryInfo rei = new ReportEntryInfo();
rei.EntryID = Convert.ToInt16(entryID);
rei.ReportPeriodID = Convert.ToInt16(reportPeriodID);
rei.ReportPeriodName = (from rp in db.ReportPeriods where rp.ReportPeriodID == rei.ReportPeriodID select rp.ReportPeriodName).FirstOrDefault();
reiList.Add(rei);
}
rc.ReportPeriodEntries = reiList;
List<ReportSchoolInfo> rsiList = new List<ReportSchoolInfo>();
foreach (string s in Request["Schools"].ToString().Split(','))
{
ReportSchoolInfo rsi = new ReportSchoolInfo();
rsi.SchoolID = Convert.ToInt16(s);
List<School> sList = db.Schools.Where(sc => sc.SchoolID == rsi.SchoolID && sc.IsActive == true).ToList();
foreach (School sl in sList)
{
rsi.SchoolName = sl.SchoolName;
rsi.SchoolLevelID = sl.SchoolLevelID;
rsi.DistID = sl.DistID;
rsi.DistName = sl.District.DistName;
}
rsiList.Add(rsi);
}
rc.Schools = rsiList;
rc.IndicatorID = indicatorID;
if (form["ComparisonSideBySide"] == "School")
rc.ComparisonSideBySide = ComparisonSideBySideValue.School;
else
rc.ComparisonSideBySide = ComparisonSideBySideValue.Entry;
rc.IncludeNarrative = Convert.ToBoolean(form["IncludeNarrative"]);
if (ModelState.IsValid)
{
if (indicatorID == 1)
{
if (rc.ComparisonSideBySide == ComparisonSideBySideValue.School)
return RedirectToAction("Leadership_sch");
else
return RedirectToAction("Leadership_entry");
}
else
{
ViewBag.ReportChooser = rc;
return View();
}
}
else
{
ViewBag.ReportChooser = rc;
return View();
}
View
#model IEnumerable<ImpactIndicator.Models.ReportDataModel>
#{
ViewBag.Title = "Report";
ImpactIndicator.Models.ReportChooser reportChooser = ViewBag.ReportChooser;
}
<hgroup class="title">
<h2>Report: Leadership</h2>
</hgroup>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
}
ReportChooser Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace ImpactIndicator.Models
{
public enum ComparisonSideBySideValue { School, Entry };
public class ReportChooser
{
public int IndicatorID
{
get
{
if (HttpContext.Current.Session["ReportChooser_IndicatorID"] != null)
return Convert.ToInt16(HttpContext.Current.Session["ReportChoose_IndicatorID"]);
else
return 0;
}
set
{
HttpContext.Current.Session["ReportChooser_IndicatorID"] = value;
}
}
public List<ReportSchoolInfo> Schools
{
get
{
if (HttpContext.Current.Session["ReportChooser_SchoolInfo"] != null)
{
List<ReportSchoolInfo> schools=(List<ReportSchoolInfo>)HttpContext.Current.Session["ReportChooser_SchoolInfo"];
schools.OrderBy(t=>t.DistName).ThenBy(t=>t.SchoolName);
return schools;
}
else
return null;
}
set
{
HttpContext.Current.Session["ReportChooser_SchoolInfo"] = value;
}
}
public int SchoolLevelID
{
get
{
if (HttpContext.Current.Session["ReportChooser_SchoolLevelID"] != null)
return Convert.ToInt16(HttpContext.Current.Session["ReportChoose_SchoolLevelID"]);
else
return 0;
}
set
{
HttpContext.Current.Session["ReportChooser_SchoolLevelID"] = value;
}
}
public List<ReportEntryInfo> ReportPeriodEntries
{
get
{
if (HttpContext.Current.Session["ReportChooser_ReportPeriodEntries"] != null)
return (List<ReportEntryInfo>)HttpContext.Current.Session["ReportChooser_ReportPeriodEntries"];
else
return null;
}
set
{
HttpContext.Current.Session["ReportChooser_ReportPeriodEntries"] = value;
}
}
public bool IncludeNarrative
{
get
{
if (HttpContext.Current.Session["ReportChooser_IncludeNarrative"] != null)
return Convert.ToBoolean(HttpContext.Current.Session["ReportChooser_IncludeNarrative"]);
else
return false;
}
set
{
HttpContext.Current.Session["ReportChooser_IncludeNarrative"] = value;
}
}
public ComparisonSideBySideValue ComparisonSideBySide
{
get
{
if (HttpContext.Current.Session["ReportChooser_ComparisonSideBySide"] != null)
return (ComparisonSideBySideValue)HttpContext.Current.Session["ReportChooser_ComparisonSideBySide"];
else
return ComparisonSideBySideValue.Entry;
}
set
{
HttpContext.Current.Session["ReportChooser_ComparisonSideBySide"] = value;
}
}
public ReportChooser()
{
}
}
}
ReportDataModel Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ImpactIndicator.Models
{
public class ReportDataModel
{
public int IndicatorID { get; set; }
public int ReportPeriodID { get; set; }
public int EntryID { get; set; }
public int SchoolID {get; set;}
public bool IsSchoolRequiredToReport { get; set; }
public int? SchoolEntryID { get; set; }
public int? IndDomainID {get; set;}
public int? IndLevelID {get; set;}
public int? IndQuestionID {get; set;}
public string Response { get; set; }
public ReportDataModel()
{
}
}
}
You can access to variables stored in session using this
var variable = (Cast the type of variable)HttpContext.Current.Session["the key"];