0

I want to send Date to Controller by using bootstrap Date-time Picker but getting error

The parameters dictionary contains a null entry for parameter 'date' of non-nullable type 'System.DateTime' for method

Here is my model class

public class Slot
    {
        public DateTime DateSlots { get; set; }

        public DateTime Starttime { get; set; }

        public DateTime EndTime { get; set; }
    }

Controller

[httPost]
public ActionResult Createslots(string startTime, string endTime, DateTime date)
        {
            using (MYDb db = new MYDb())
            {
                Slot obj = new Slot();
                obj.Starttime = Convert.ToDateTime(startTime);
                obj.EndTime = Convert.ToDateTime(endTime);
                obj.DateSlots = date;
                db.Slots.Add(obj);
                db.SaveChanges();
            }
            return View();
        }
 // my Action
 public ActionResult Createslots()
        {
            return View();
        }

View

   @using (Html.BeginForm("Createslots", "slot", FormMethod.Post))

    {
                    <div class="col-sm-6 form-group">
                        @Html.LabelFor(model => model.DateSlots )
                        @Html.EditorFor(model => model.DateSlots , new { htmlAttributes = new { @class = "form-control" } })
                    </div>
                    <div class="col-sm-6 form-group">
                        @Html.LabelFor(model => model.Starttime)
                        @Html.EditorFor(model => model.Starttime, new { htmlAttributes = new { @class = "form-control" } })
                    </div>
                    <div class="col-sm-6 form-group">
                        @Html.LabelFor(model => model.EndTime)
                        @Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { @class = "form-control" } })
                    </div>
                    <input type="submit" class="btn text-center" value="Submit" style="background: rgb(15, 94, 125);" />
}

here is Front end Img

start time and end time i easily get but when i try with Date then getting this of type Error

The parameters dictionary contains a null entry for parameter 'date' of non-nullable type 'System.DateTime' for meth

Note i also try null-able i case of date store null

 public ActionResult Createslots(string startTime, string endTime, DateTime ? date)
        {
}
  • I find when working with dates, it's easier to treat them as strings and then Convert them to DateTime on the backend or when inserting into the database. Since your ActionResult is expecting strings for start and end, why not just make all three Model properties strings, since strings can be passed as null values? Or if you still want to use DateTime objects inside your Model, change your coresponding Model property to a Nullable Datetime – Ryan Wilson Jun 27 '18 at 15:24
  • Please see this https://stackoverflow.com/questions/1650958/non-nullable-type-system-datetime-asp-net-mvc – Hitesh Anshani Jun 27 '18 at 15:25
  • @RyanWilson i try tis but getting this error The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated. – zubair zubairgone Jun 27 '18 at 15:35
  • @zubairzubairgone Sounds like a problem passing your datetime to sql, (https://stackoverflow.com/questions/1331779/conversion-of-a-datetime2-data-type-to-a-datetime-data-type-results-out-of-range) – Ryan Wilson Jun 27 '18 at 15:41
  • @RyanWilson "I find when working with dates, it's easier to treat them as strings and then Convert them to DateTime on the backend or when inserting into the database"...this just makes it harder to validate the model at an early point in the process because the date parsing has to happen manually. There's no advantage to this. MVC can parse the strings submitted in the request (they're always strings when they're being transmitted, of course) as Dates no problem, provided the string provided is in a valid format. – ADyson Jun 27 '18 at 15:50
  • @ADyson Depends on how you do validation, I sometimes use JQuery Validation or my own custom validation on the front end before even submitting something to the server. – Ryan Wilson Jun 27 '18 at 15:51
  • @RyanWilson client-side validation is trivial to bypass, it's nice for UX but doesn't provide any actual protection to your application – ADyson Jun 27 '18 at 15:55
  • @ADyson I typically do both client and server side validations. But you have made a good point. :) – Ryan Wilson Jun 27 '18 at 16:01

3 Answers3

1

This is happening because when using the MVC framework, the values are submitted from view to controller via the name of the HTML element.

In your form, you have 3 textboxes:

DateSlots - StartTime - EndTime

So, when you use the Html.EditorFor template like so:

@Html.EditorFor(model => model.DateSlots , new { htmlAttributes = new { @class = "form-control" } })

That translates into HTML like so:

<input type="text" id="DateSlots" name="DateSlots" class="form-control" />

So, in your controller you are expecting a value based on the parameter name of date, but notice above the name is DateSlots.

In short, you just have to change the name of your parameter to dateSlots:

[HttPost]
public ActionResult Createslots(string startTime, string endTime, DateTime dateSlots)

OR

BETTER SOLUTION

Seeing as though you're using EditorFor you are using a Model/Class (Slots) at the top of your view, so you could just do this in your controller:

[HttPost]
public ActionResult Createslots(Slot mySlot)
{
    using (MYDb db = new MYDb())
    {
        Slot obj = new Slot();
        obj.Starttime = Convert.ToDateTime(mySlot.StartTime);
        obj.EndTime = Convert.ToDateTime(mySlot.EndTime);
        obj.DateSlots = mySlot.DateSlots;
        db.Slots.Add(obj);
        db.SaveChanges();
    }
    return View();
}

I hope this helps.

Grizzly
  • 5,873
  • 8
  • 56
  • 109
  • Ok Yes its working but i get value form date-picker not from – zubair zubairgone Jun 27 '18 at 15:42
  • 1
    How are you telling the `EditorFor` for `DateSlots` to use date-picker? – Grizzly Jun 27 '18 at 15:43
  • [DataType(DataType.Date)] public DateTime DAteSlots{ get; set; } when we create property like this it show automatically date-picker :) – zubair zubairgone Jun 27 '18 at 15:46
  • @zubairzubairgone what do you mean? Surely the datepicker just places the selected date value back into the textbox in order to be submitted? If it doesn't it should. IMO using the strongly-typed `Slot` viewmodel to receive data into the CreateSlots action is the correct way to go, this is how MVC is intended to be used. – ADyson Jun 27 '18 at 15:46
  • @ADyson please read my question which i show Img and i select this date by time-picker – zubair zubairgone Jun 27 '18 at 15:49
  • 1
    I'm confused as to how date-picker is the problem. Your question is asking why the value isn't being submitted to the controller.. My solution should resolve that. – Grizzly Jun 27 '18 at 15:50
  • @zubairzubairgone I already did. There is no time- or date-picker shown in your image – ADyson Jun 27 '18 at 15:51
  • 1
    @ADyson Agreed. I think this date-picker conversation is getting away from the main issue. It shouldn't matter now if the OP is using date-picker to select dates or if they're manually typing in dates.. Whichever value is in that textbox now, should submit to the controller. – Grizzly Jun 27 '18 at 15:52
  • @zubairzubairgone If it still isn't working, the only thing I can think, looking at the picture which shows "06/08/2018", is that you are sending the date in an ambiguous format - it could be dd/mm/yyyy or mm/dd/yyyy. 6th August or 8th June. I can't tell, and equally the server has no way to know which format you intended either. Better to submit it in an unambiguous format such as yyyy-mm-dd. Either that or ensure your server application's culture is set to one which has one of those date formats as its standard format. This is not really related to the datepicker specifically. – ADyson Jun 27 '18 at 15:54
  • 2
    @zubairzubairgone if this answers your question, please mark this answer as accepted so that the question can be seen as answered. – Grizzly Jun 27 '18 at 16:14
1

I think it is because you have a parameter named date in the action but you send argument with the name DateSlosts. So, the model binder cannot bind your property. If you do not want to change the names, you can use [Bind(Prefix = "DateSlots")] before the action parameter date.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
1

You can pass the model as a parameter as opposed to each individual property and avoid conversions altogether:

[HttpPost]
public ActionResult Createslots(Slot slot)
{
  using (MYDb db = new MYDb())
  {
    db.Slots.Add(slot);
    db.SaveChanges();
  }
  //return to whatever
}

Additionally, you can use the DisplayFormat attribute in your model and utilize the HTML5 date picker in your view:

public class Slot
{
  [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  public DateTime DateSlots { get; set; }
  [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  public DateTime Starttime { get; set; }
  [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  public DateTime EndTime { get; set; }
}

View:

@Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { @class = "form-control", type= "date" } })
Matt Ashurst
  • 306
  • 1
  • 7
  • Yes, passing the entire model to the controller action will work rather than having to do each individual property.. but the point is, is that the name of the parameter is different from the name of the element on the form. – Grizzly Jun 27 '18 at 15:47
  • @M12Bennett True. But the point should be the issue could be ignored entirely with a little less coding and focusing on best practices. – Matt Ashurst Jun 27 '18 at 15:56
  • 1
    No disagreement with you there. I am just stating that your answer will work, but please explain why their current practice is not. It's mutually beneficial for you and the OP since you can teach/explain why and the OP can learn from their mistakes. Most importantly, it reinforces the OP's understanding about the fundamental concepts of how the MVC framework operates. – Grizzly Jun 27 '18 at 15:58