简体   繁体   中英

ASP.NET MVC 5 “When ModelState is Invalid”

I have a bit of problem in asp.net mvc. I am going to post the entire code and then i explain it.

ViewModel.

public class EventFormViewModel
{
   [Required]
   public string studentId{ get; set; }
   [Required]
   public string location{ get; set; }
   [Required]
   public string Date { get; set; }
   [Required]
   public string Time { get; set; }

  // Date and Time == DataTime.
  public DateTime GetDateTime()
  {
      var Datetime = DateTime.Parse(string.Format("{0} {1}", Date, Time));
      return Datetime;
  }
}

When the model state is invalid the mvc framework -- The mvc framework called this action method and uses the reflection to construct this viewmModel (All Properties only not a method.) and in this case the GetDateTime() is method. Why i am getting this exception ?

Controller

        [Authorize]
        [HttpPost]
        public ActionResult NewEvent(EventFormViewModel viewModel) 
        {
            if (!ModelState.IsValid)
            {
                 return RedirectToAction("Index","Home");
            }

            var _event= new _Event
            {
                studentId = User.Identity.GetUserId(),
                DateTime = viewModel.GetDateTime(),
                location = viewModel.location
            };

            _Dbcontext._Events.Add(_event);
            _Dbcontext.SaveChanges();

            return RedirectToAction("Index","Home");
        }

When i run my code. i getting this error.

在此处输入图片说明

Problem: In my viewModel marked all the fields required. S0 when i submit empty form i am getting this "String Was not recongnize as a valid DateTime" Exception.

The input can be correct date and time format and as you said user might not provide that. You can use TryParse method which will safely parse if it is a valid date time value. So you can write :

DateTime parsedDateTime;
bool isParsed = DateTime.TryParse(string.Format("{0} {1}", Date, Time),out parsedDateTime);

return parsedDateTime;

or alternativley you need to check if the date and time both are provided then parse them by checking with an if condition:

public DateTime GetDateTime()
{
  DateTime dateTime = DateTime.MinValue;
  if(!String.IsNullOrEmpty(Date) && !String.IsNullOrEmpty(Time))
       dateTime= DateTime.Parse(string.Format("{0} {1}", Date, Time));

  return dateTime;
}

Try this. I have tested it and it works perfectly:

public DateTime GetDateTime()
{
    var inputDate = DateTime.ParseExact(this.Date, "dd/MM/yyyy", CultureInfo.InvariantCulture); 
    var inputTime = TimeSpan.Parse(this.Time);
    DateTime datetime = inputDate + inputTime;
    return datetime;
}

In the above code instead of "dd/MM/yyyy" use your own format in which date is being sent from the UI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM