c# - ASP.NET MVC DateTime Parse -


i've made simple web application , it's work correctly on local db. after publishing, there error connected datetime:

system.formatexception: string not recognized valid datetime. 

the code in viewmodel looks this:

[required] [validtime] [display(name = "game time")] public string time { get; set; } [required] [futuredate] [display(name = "game date")] public string date { get; set; } public datetime getdatetime() {     return datetime.parse(string.format("{0} {1}", date, time));           } 

controller code:

public actionresult create(gameformviewmodel viewmodel) {     if (!modelstate.isvalid)         return view("gameform", viewmodel);     var userid = user.identity.getuserid();     var game = new game     {         teama = viewmodel.teama,         teamb = viewmodel.teamb,         datetime = viewmodel.getdatetime(),         leagueid = viewmodel.id,         adminid = userid      };      _context.games.add(game);     _context.savechanges();       return redirecttoaction("myleagues", "leagues"); } 

why it's work @ local db , why there error after publishing ?

update: thats futuredate class

public class futuredate : validationattribute {     public override bool isvalid(object value)     {         datetime datetime;         var isvalid = datetime.tryparseexact(convert.tostring(value),             "dd-mm-yyyy",             cultureinfo.currentculture,             datetimestyles.none,             out datetime);            return (isvalid && datetime >= datetime.now.adddays(-1));      } } 

the error has custom validation attributes (validtime or futuredate). there's no other code here might potentially generate exception.

however, way you're going bad in first place, , if right way, won't issue. you'll have less bugs in general, right now, if invalid date/time value posted, whole app going explode.

change properties on view model to:

[required] [display(name = "game time")] [datatype(datatype.time)] public timespan? time { get; set; }  [required] [futuredate] [display(name = "game date")] [datatype(datatype.date)] public datetime? date { get; set; } 

then, getdatetime method becomes:

public datetime getdatetime() {     return date.hasvalue && time.hasvalue ? date.add(time) : default(datetime); } 

by making time , date properties timespan , datetime, respectively, modelbinder handle conversion posted string values. if either cannot converted respective types, default value (null) filled instead, trigger required validation. getdatetime method, doesn't have parse anything; adds 2 if have value.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -