Passing DateTime into TryUpdateModel - asp.net-mvc-3

One property of my model is DateTime. I'm working with DateTime format "d.M.yyyy H:mm", i.e. day.month.year. When I pass date like 11.4.2011 (April 11th, 2011) into TryUpdateModel, it comes back as 4.11.2011, i.e. day and month swaps. Is there any way how can I instruct TryUpdateModel to parse datetime value the way I want, not the way system wants?
Thanks,
Antonin

I had the same problem and I discovered that if I use HTTPPost instead of HTTPGet MVC behaves as expected. I don't know why it solves the problem and I am still looking for the full answer to this question.

Related

Trouble passing DateTime values to WebApi route

I have a WebApi project where I have a method that takes a start date and an end date, runs a report, and returns the results. I'm trying to come up with the route for this and so far its looking like
/api/MarketingEmailStatisticsReports/DateRange/{startDate}/{endDate}
Perhaps there is a better route but that really isn't the problem.
I was testing this by simply opening a browser and typing the URL. If I set the startDate and endDates as DateTime fields, I get a 404 Not Found. If I make them strings, I can enter the method but the dates aren't parsable when I attempt to convert them from strings to actual DateTime values.
I realize that if I use "/" characters in the date that will be a problem so I did attempt to use "-" characters as the separator between the month-day-year values.
After looking at some of the Microsoft documentation, I saw how you can put route constraints to check for a DateTime values as well as a regular expression to make sure the value was entered in the correct format. I have taken this advice and am using the following:
[HttpGet]
[ResponseType(typeof(MarketingEmailStatisticsReport))]
[Route("/api/MarketingEmailStatisticsReports/DateRange/{startDate:datetime:regex(^\\d{4}-\\d{2}-\\d{2}$)/{endDate:datetime:regex(^\\d{4}-\\d{2}-\\d{2}$)}")]
public IHttpActionResult Get(DateTime startDate, DateTime endDate)
I get this exception:
ArgumentException: parsing
"^\d{4}-\d{2}-\d{2}$)/{endDate:datetime:regex(^\d{4}-\d{2}-\d{2}$" -
Too many )'s.
This is the URL I was using:
api/MarketingEmailStatisticsReports/DateRange/2017-05-22/2017-05-23
It doesn't look to me that I have too many ")" characters... What do I need to do to get this to work, or should I pass the dates on the querystring instead?
You forgot to close startDate parameter definition:
.../DateRange/{startDate:datetime:regex(^\\d{4}-\\d{2}-\\d{2}$)}/{endDate:datetime...
^
this curly bracket

Datepicker date format on server

I have a probleme with date picker I have already created controllers with read/write actions and views using EF everything was OK
Till I have need to create a controller with a modelView so I chosed an empty controller and I created the views by myself
The problem is when I use datepicker with dd/MM/yy it is shown OK but when I check the value sent to the server it's null if day is >12
I tried to introduce 02/19/2008 it accepts it in the server it is sent as 19/02/2008
I didn't understand why
I try to set globalization culture and uiculture to en-US en-GB fr-FR nothing work
Is there a way to specify how date picker parse the date( I already used the datepicker.parseDate)
Need your help please
You could specify the desired format when creating the datepicker:
$('#datepicker').datepicker({ dateFormat: 'dd/mm/yyyy' })
Now you should also make sure that your server uses the same format for parsing the date either by specifying a culture or you could also write a custom model binder for the DateTime type.
I had that problem, and solution was putting globalization information in web.config.
like this: <globalization culture="sr-Latn-RS"/>
Just check that you place that in <system.web>.

How do I properly validate DateTime in a CRUD situation for a model within an MVC project?

I have users selecting a DateTime using a caldendar/clock popup that allows them to make a selection. However, if they were to go in and edit the date to read something like: 6/12/201 10:36:47 AM instead of 6/12/2012 10:36:47 AM my Action gets past the ModelState.IsValid check and I get an error when the Controller attempts to save the object to the database (rightly so).
How do I properly validate DateTime in this situation? (I want to prevent a user from even being able to 'submit' the form if the datetime is not properly formatted)
Note: I currently have in place jquery.validate and typically (fields not DateTime) I use #Html.ValidationMessageFor(model => model.Field) - This does not appear to do anything for my current DateTime fields when they are formatted inappropriately.
you can simply add date client side validator for you DateTime field using snipet like that:
$(element).rules('add', {
date: true,
});
where "element" is your input for DateTime field.
Are you sure you're importing all of the requisite validation js files? it sounds like your server validation is working OK but the client is doing nothing. I suggest reading the following post by Brad Wilson: link

MVC 3 update entity with DateTime property

I have a MVC 3 project that uses Entity Framework. I can successfully update entities like this:
[HttpPost]
publiv RedirectResult Update(MyEntity entity)
{
if(ModelState.IsValid)
{
this.entityRepository.Update(entity);
return RedirectResult(".../Admin");
}
return RedirectResult(".../UnssuccessfullOperation");
}
Now the problem arised when I added DateTime property to my entities. If I do not add the #Html.HiddenFor for my DateTime property the date of my entity is 01.01.0001 (or DateTime.Min), which obviously cannot be saved to the database. If I add the hidden input the date is rendered but on update my ModelState is not valid and I guess this is due to the fact that the datetime is passed as a string.
Now there is one solution, but it seems a little strange - to not render Html.Hidden in the view and to use the datetime from the entityRepository like this:
entity.DateSomething = this.entityRepository.GetSingle(entity.ID).DateSomething;
but it does not seem very correct. Are there any other better options in that case?
If I add the hidden input the date is rendered but on update my
ModelState is not valid and I guess this is due to the fact that the
datetime is passed as a string.
No, I suspect that it's due to the culture setting in your application and the datetime format used in the hidden field. They probably don't match.
Take a look at the following blog post which covers the different issues that arise when parsing dates and how the format will depend on whether you are doing a GET or POST request and also a possibility to write a custom model binder to use a fixed format for dates.

Set date format in ruby model (sinatra/datamapper)

I have a ruby model that contains a date attribue which I'd like to be able to pass in as a parameter in the format dd/MM/yyyy.
However, my sqlite3 db stores the data in yyyy-MM-dd format so when a date like 20/10/2010 gets passed in, it will not be read to the database.
I am using the Sinatra framework and using haml for the markup creation.
Do I need to write a helper that takes the date string and converts it to the correct format for the db? Or can I set a format type on the models attribute?
Thanks.
You shouldn't need to worry about the database's internal representation of the date; DataMapper is there to do that for you. You just need to make sure you are passing it a valid Date object.
Check out http://ruby-doc.org/core/classes/Date.html for methods available to the Date class. For your example:
require 'date'
mydate = '20/10/2010'
mydate_obj = Date::strptime(mydate, '%d/%m/%Y')
puts "#{mydate_obj}" # prints 2010-10-20
I don't know if this can help, some time ago I had the same problem: I was using Rack::Utils.escape_html(params[:datetime]) to escape html on user input and if I typed a date in a form field like this "25/02/2013" it would be sent to the DataMapper model like this: 16/02/2013 (with escaped html codes) so it was saving it the wrong way (day ended up being the hour or something similar).
Maybe you are also using "escape_html" method in an awkward way?

Resources