Daza Aza
Daza Aza

Reputation: 498

Date picker not saving to database

Problems with wiring up datepicker

The code for partial view

@model System.DateTime
@Html.TextBox("", Model.ToString("dd/MM/yy"), new { @class = "date" })

The code for the view

 @Html.TextBox("DateTime", (Model.AdvertStartDate.ToString()), new { @class = "date" })

Scripts

 <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

Code used for datepicker

<script type="text/javascript">
    $(document).ready(function () {
        $('.date').datepicker
        ({
            dateFormat: 'dd/mm/yy',
            showStatus: true,
            showWeeks: true,
            currentText: 'Now',
            autoSize: true,
            gotoCurrent: true,
            showAnim: 'blind',
            highlightWeek: true

        });
    });
</script>

Code for model

 [Required]
   public DateTime AdvertStartDate { get; set; }

The date is inserting into the textbox but is not updating in the database

Can you suggest anything that is missing?

Upvotes: 0

Views: 1768

Answers (2)

y.selivonchyk
y.selivonchyk

Reputation: 9885

Datapicker is not the easy element to implement in MVC application.

Try condsider next things:

  1. Make sure that data from data picker is sent to server (datapicker should have appropriate name)
  2. Make sure that datapicker dataformat is the same as your application data format (which can differ depanding on chosen culture) - in that case data is sent to server, but not always valid because 31.01 get be transated as month 31, date 1.

Upvotes: 0

Slauma
Slauma

Reputation: 177163

I think the HTML <input> element rendered by TextBox("DateTime",...) doesn't have the correct name (the name will be "DateTime"), so it doesn't get bound correctly to your model property AdvertStartDate when the data are posted to the server.

Your "partial view" looks like an EditorTemplate to me. In this case you should be able to just use this in your view:

@Html.EditorFor(model => model.AdvertStartDate)

Because AdvertStartDate is of type DateTime the EditorTemplate including the DatePicker should be used to render the input element.

If the EditorTemplate file has another name than DateTime.cshtml - like AnotherTemplateName.cshtml - you can specify the template explicitly:

@Html.EditorFor(model => model.AdvertStartDate, "AnotherTemplateName")

Upvotes: 1

Related Questions