How to specify date format for model binding? - datetime

I hope the question is easy, but I am searching around for more than an hour and I just do not find the answer. So I have a asp.net mvc 2 application and one of the forms contains a date textbox with a jquery datepicker. I have set in the datepicker the date format to be dd.mm.yyyy. My problem is that on the model binding this date is interpreted as mm.dd.yyyy, so by the time the model reaches my action method the DateTime attribute of the model is not correct (day and month is reversed, if it is not possible to reverse it client side validation does not let me save the item). I do not want to change culture, but I would like to specify somehow to the model binder how to interpret the date. Is it possible somehow?
Thanks a lot

This blog post explains how you can specify a particular date format to be used by the MVC model binder.
You will need to create a custom model binder implementation that is aware of the date format, then associate that with the DateTime type in your Global.asax.cs:
protected void Application_Start()
{
//...
var binder = new DateTimeModelBinder(GetCustomDateFormat());
ModelBinders.Binders.Add(typeof(DateTime), binder);
}

You might find the answer to your question here
Custom DateTime model binder in Asp.net MVC
Also Scott Hanselman has talked about a DateTime custom model binder here
http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx
Although he's using the binder to split the date & time you might his post useful when creating your custom model binder.

Related

Date model binding in ASP.NET Core

I'm building one ASP.NET Core Web API and I've recently found one issue regarding the binding of DateTime values.
In truth I have one minimumDate and one maximumDate properties for filtering in a certain resource. These are part of one Filtering object which just gets populated on the controller by model binding.
The issue is that the request is sent like this:
minimumDate=2014-01-20T00:00:00.000Z&maximumDate=2014-03-21T00:00:00.000Z
and on the controller one gets when debuging:
MinimumDate = 19/01/2014 22:00:00
MaximumDate = 20/03/2014 21:00:00
This is clearly wrong. The expected was:
MinimumDate = 20/01/2014 00:00:00
MaximumDate = 21/03/2014 00:00:00
It is reducing one day in both the minimum and maximum dates and furthermore it is messing the time part.
I thought at first it had to do with culture and globalization, but this is already set in the Startup configure method as:
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("pt-BR");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("pt-BR");
so I doubt this to be the reason.
What am I doing wrong? How to get dates properly being sent to the API with model binding?
EDIT I managed to solve the issue by manualy parsing the datetime objects using:
filtering.MinimumDate = DateTime.Parse(this.Request.Query["minimumDate"], null, System.Globalization.DateTimeStyles.RoundtripKind);
filtering.MaximumDate = DateTime.Parse(this.Request.Query["maximumDate"], null, System.Globalization.DateTimeStyles.RoundtripKind);
In other words, bypassing the model binder. Still, I want to know: why model binding is presenting this strange behavior here?
To me it looks like the model binder which uses Json.net behind the scenes is converting your UTC time to local time for BRT (UTC-3) which is why you see the date and time change. You should be able to update your JsonSerializerSettings property as:
new JsonSerializerSettings
{
.....
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
.....
}
That should take care of proper model binding in your case.

How can I transform posted XML to a POCO in an MVC action?

I have the following method signature for an action on an MVC controller:
public ActionResult DoSomething(int id, string anotherParameter, IEnumerable<StronglyTypedThing> data)
{
}
This method is called by an AJAX Request (in this instance I'm using ExtJS, but that should have little/no bearing on this I imagine!) which passes up, for example:
id: 1,
anotherParameter: 'cake',
data: '<stronglyTypedThings>
<stronglyTypedThing>
<id>1</id>
<anotherProperty>Smith, John></anotherProperty>
</stronglyTypedThing>
<stronglyTypedThing>
<id>2</id>
<anotherProperty>Doe, Jane></anotherProperty>
</stronglyTypedThing>
</stronglyTypedThings>'
Currently the method signature I've shown above is not what I have, instead the final parameter is defined as string data and I have what is effectively boilerplate code which transforms the XML string into an IEnumerable<StronglyTypedThing>.
Is there a way to have (either by virtue of something baked into MVC, or by extending it) MVC deal with the grunt-work for me so I don't have the boilerplate code present in my action method?
You can create a custom model binder.
This link will have an example of custom xml binder: http://lostechies.com/jimmybogard/2011/06/24/model-binding-xml-in-asp-net-mvc-3/
You might want to look into a custom ValueProviderFactory.
A custom XmlValueProviderFactory will parse the incoming xml string and construct an intermediate dictionary. (which MVC uses to model bind)
Based on your need, you could parse the whole XML/or a part of it, to construct the dictionary equivalent of your Model object. Once there, MVC will take care of creating the Model for you using Model Binding. Also, value providers have the additional benefit of input validation which custom model binders don't have.
Please see following help links to see a JSON & XML Value Provider factory.
i think the JSON Value provider is now in built, but not the XML one. not sure.
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx/
http://www.nogginbox.co.uk/Media/files/XmlValueProviderFactory.txt

Asp.net mvc 2 custom view model: where would the validation attributes go?

I've been chugging along OK with the use of data annotations made on buddy classes so far.
When it comes to a more complex view that requires a custom view model--one that includes a few select lists, for example...would I need to then transfer my validation attributes to the view model class?
I was planning to pass the full custom view model to populate an "Edit" view, but was hoping to just receive a simple object in my "Save" action.
Where are the flaws in this plan, or is the whole thing just one big pile of fail in the first place?
Thank you.
You're still validating that data that is ultimately going back into the database. So in order to keep your application DRY, you are best off to use the Buddy Classes for the original Model.
Edit
note: this doesn't exactly have anything to do with your question
I personally prefer extend the original Model for anything "Edit" related and I prefer to use a ViewModel for "Display" only (Details pages, List pages, etc).
Example: here's my buddy class, and in it I've added a "RegionName" property that I use in the Edit Page display, but it doesn't have anything to do with the database. You can do a similar thing with custom input data that you want to validate before manipulating it into "database usable" data. I use the RegionID in the database, but I prefer to use the friendly name for the visitor instead of the ID integer
<MetadataType(GetType(UserMetaData))> _
Partial Public Class User
Public RegionName As String
End Class
Public Class UserMetaData
<DisplayName("region name")> _
<Required(ErrorMessage:="region name is required.")> _
Public Property RegionName As String
End Class
Your view model will still inherit the validation from your base model.
Don't know if this helps but I put my validation attributes against my model so that wherever i use the model i get the same validation. not ideal for some projects i realise.
actually, i put the attributes agains a partial class rather than my model because 90% of the time my model comes from a linq 2 sql file in my data repository
my controller then simply checks if the model is valid or not and the view does nothing except display data and errors really.
unsure if this is what you're asking though

xVal Date Validation with Nhibernate Validator

I am using xVal with NHibernate Validator and I have a hard time to validate the dates.
First, NHibernate does not have validation for Date/DateTime formatting (except Past and Future). Second, I tried xVal itself (not using NHibernate Validator) but still no chance.
I need to validate the date values (let's say in a text box), to make sure it's a valid date. For instance, 13/01/2010 or 11/31/2010 are not valid dates.
I have tried creating new rules for NHibernate Validator by extending a new class, but it needs to be declared in the xVal client side too. I don't like to overwrite the existing scripts, if possible. I also used xval's [DataType(DataType.Date)] but it doesn't check if the date is valid!
Any suggestions?
After spending some time on this issue, here is the answer to my question: Custom Validation in xVal

ASP.NET MVC model binding and action parameters

Let's say I have a controller action defined as:
public ActionResult(MyModel model, string someParameter)
{
// do stuff
}
I have a custom model binder for the MyModel type, and there is a form field called "SomeParameter" in the view that is not bound to the model. How does ASP.NET MVC know to pass the value of Request.Form["SomeParameter"] as the value for the "someParameter" argument to the action?
ASP.NET uses reflection to determine the correct method to invoke and to built up the parameters to pass. It does so based on the FormCollection array. Basically it will see model.* Keysin there and a FormCollection["someParameter"] it will first try Action(model,someParameter) then Action(model) and then Action(). Since it finds an Action with a model and someParameter arguments it will then try to convert them into the arguments types.
However by default it does so blindly which introduces some security risks, this blog post goes into greater detail on this.
If anyone can post up a link which in greater detail describes how ModelBinding is done under the hood that would be great.
Because the default model binder will be used for someParameter unless you specify otherwise. And the default model binder does exactly what you describe.
Phil Haack has a post on How a Method becomes an Action which explains just how this resolution happens.
Sounds like you need a model binder. These allow you to define how form data is bound to a model parameter. You can read more about them at the following:
ASP.NET MVC Preview 5 and Form Posting Scenarios
How to use the ASP.NET MVC Modelbinder
One of the easiest way is having Html items on the page with same name as the input parameters in the action method.
EX) In the View we have:
<input name="refNo" type="text">
Then in the Action method:
public ActionResult getOrders(string refNo)
So, it simply bind the value of "refNo" to the input parameter of the "getOrders" action.

Resources