Search code examples
asp.net-mvcdatedatetimepostjquery-multidatespicker

How to receive dates from multidatespicker in a List<Datetime> ASP NET MVC?


In my program, I have implemented multidatespicker (http://multidatespickr.sourceforge.net/) for my solution. I have an attribute called DatesDispo to receive my dates picked from my calendar.

public List<DateTime> DatesDispo { get; set; }

In my razor view, I have an input for my calendar:

<div class="form-group">
    @Html.LabelFor(model => model.DatesDispo, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <input name="DatesDispo" id="DatesDispo"></input>
    </div>
</div>

I see my calendar and until there it's working. But on post of the form, I don't receive my dates that I picked in my DateDispo field. In debug mode, I had tested this and it worked but maybe I changed something and now I'm unable to bind dates picked with my date field. Someone know why? I swear that I had picked 2 dates and my list of dates had a count = 2.

Edited: Data received from post => https://gyazo.com/629a7f01c6802b2cefc825d786b2470b

__RequestVerificationToken=FG381kMw0ANq_vV0ucoFr7Rrn6J1nqZNptlSy9JtT27JUggqOvru9Q‌​FkPZP40QniZ_ZBtpBNzMN00MZA5Aq06ZByz3yAz9-YNXpNjMhOG0o1&IdHabilete=7&Adresse=&Vill‌​e=&CodePostal=&Pays=&Province=&DateMax=2016-01-26+13%3A42%3A23&DateCreation=2016-‌​01-26+13%3A42%3A23&DatesDispo=01%2F28%2F2016%2C+01%2F29%2F2016&Specifications=Sys‌​tem.Collections.Generic.List%601%5BFavornet.Models.Biz.SpecDemande%5D DatesDispo=01%2F28%2F2016%2C+01%2F29%2F2016

DatesDispo field extracted from above

DatesDispo=01%2F28%2F2016%2C+01%2F29%2F2016

Solution

  • Although you intend to post a collection of dates. You are posting a single field as a single string. In this case the auto binding doesn't have a problem with a single date but can't recognize the way you send multiple dates.

    <input name="DatesDispo" id="DatesDispo"></input>
    

    A single input is sending as

    DatesDispo=01%2F28%2F2016%2C+01%2F29%2F2016
    

    Or

    "01/28/2016, 01/29/2016"
    

    One solution is to send it as string that needs to be parsed back into a collection.

    public class SomeModel
    {
        public string DatesDispo { get; set; }
    }
    
    [HttpPost]
    public ActionResult SendDates(SomeModel model)
    {
        List<DateTime> dates = new List<DateTime>();
        var datesDispo = model.DatesDispo.Split(',');
    
        foreach(var date in datesDispo)
        {
            dates.Add(DateTime.Parse(date));
        }
    
        ...
    }