Hi guys, I'm following an example from a book (incidentally I'm amazed how many mistakes I've found in pretty much all the MVC books I've so far consulted) and I think I've found where the error is by going line by line, compile and executing the app. Basically, this is the controller:
public ActionResult Details(long id = 0)
{
var auction = new Auction
{
Id = id,
Title = "Brand new Widget 2.0",
Description = "This is a brand new version 2.0 Widget!",
StartPrice = 1.00m,
CurrentPrice = 13.40m,
// StartTime = DateTime.Parse("6-15-2012 12:34 PM"),
//EndTime = DateTime.Parse("6-23-2012 12:34 PM")
};
return View(auction);
}
and here is my model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ebuy.Website.Tests.Models
{
public class Auction
{
public long Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public decimal StartPrice { get; set; }
public decimal CurrentPrice { get; set; }
//public DateTime StartTime { get; set; }
//public DateTime EndTime { get; set; }
}
}
It all looks OK but it turns out that the error is in the last to lines (here commented out) of the controller:
StartTime = DateTime.Parse("6-15-2012 12:34 PM"),
EndTime = DateTime.Parse("6-23-2012 12:34 PM"),
because when I remove them the application runs OK. Strangely enough Visual Studio doesn't pick up anything but at run time I get this:
String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: String was not recognized as a valid DateTime.
Source Error:
Line 23: public ActionResult Details(long id = 0)
Line 24: {
Line 25: var auction = new Auction
Line 26: {
Line 27: Id = id,
After having done a lot of testing (as I had absolutely no idea what was going on) and googling, it seems that Date.Parse(string)
isn't the right way to go because we need to make sure that whatever date I supply in whichever format can be parsed correctly. Some people seem to say to use ParseExact()
but it looks like they are all using it in different ways. So in the end I used these - and the app works:
StartTime = DateTime.Parse( "6-15-2012 12:34 PM", CultureInfo.CreateSpecificCulture("en-EN") ),
EndTime = DateTime.Parse( "6-23-2012 12:34 PM", CultureInfo.CreateSpecificCulture("en-EN") ),
So my question to you now is: is it really true that any country should have a different set of rules, like GB for Uk etc etc? That's madness! Does it mean that in the real world application developers need to add an awful lot of code to make sure that the app works across the globe?! Or is this just because in this specific case we are hard coding the date?