Let's say that you have a Model that looks kind of like this:
public class MyClass {
public string Name { get; set; }
public DateTime MyDate { get; set; }
}
The default edit template that Visual Studio gives you is a plain textbox for the MyDate property. This is all fine and good, but let's say that you need to split that up into it's Month/Day/Year components, and your form looks like:
<label for="MyDate">Date:</label>
<%= Html.TextBox("MyDate-Month", Model.MyDate.Month) %>
<%= Html.TextBox("MyDate-Day", Model.MyDate.Day) %>
<%= Html.TextBox("MyDate-Year", Model.MyDate.Year) %>
When this is submitted, a call to UpdateModel won't work, since there isn't a definition for MyDate-Month. Is there a way to add a custom binder to the project to handle situations like this, or if the HTML inputs are named differently (for whatever reasons)?
One workaround I've found is to use JavaScript to inject a hidden input into the form before submission that concatenates the fields and is named properly, but that feels wrong.
I would suggest you a custom model binder:
using System;
using System.Globalization;
using System.Web.Mvc;
public class MyClassBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var model = (MyClass)base.CreateModel(controllerContext, bindingContext, modelType);
var day = bindingContext.ValueProvider["MyDate-Day"];
var month = bindingContext.ValueProvider["MyDate-Month"];
var year = bindingContext.ValueProvider["MyDate-Year"];
var dateStr = string.Format("{0}/{1}/{2}", month.AttemptedValue, day.AttemptedValue, year.AttemptedValue);
DateTime date;
if (DateTime.TryParseExact(dateStr, "MM/dd/yyyy", null, DateTimeStyles.None, out date))
{
model.MyDate = date;
}
else
{
bindingContext.ModelState.AddModelError("MyDate", "MyDate has invalid format");
}
bindingContext.ModelState.SetModelValue("MyDate-Day", day);
bindingContext.ModelState.SetModelValue("MyDate-Month", month);
bindingContext.ModelState.SetModelValue("MyDate-Year", year);
return model;
}
}
This simplifies your controller action to:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(MyClass myClass)
{
if (!ModelState.IsValid)
{
return View(myClass);
}
// Do something with myClass
return RedirectToAction("success");
}
And register the binder in Global.asax:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.Add(typeof(MyClass), new MyClassBinder());
}
A simple way to handle this would be to get the values manually from the ValueProvider and construct the date server side, using UpdateModel with a white list that excludes these properties.
int month = int.Parse( this.ValueProvider["MyDate-Month"].AttemptedValue );
int day = ...
int year = ...
var model = db.Models.Where( m = > m.ID == id );
var whitelist = new string[] { "Name", "Company", ... };
UpdateModel( model, whitelist );
model.MyDate = new DateTime( year, month, day );
Of course, you'd need to add validation/error handling manually as well.
Related
I've got his code.
PartialView.
<div class="input width110">
#Html.EditorFor(x => x.Price, #Html.Attributes(#class: "right_text_align", #disabled: "true", #id: "Price"))
</div>
Model.
public class ServiceModel
{
[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public decimal Price { get; set; }
}
Controller
public ActionResult SetService(ServiceModel model, string action)
{
if (ModelState.IsValid)
{
/*Does smthg.*/
ModelState.Clear();
}
return View("Index", rcpModel);
//Index is main view, which holds partialView
//rcpModel holds, model
}
When view loads Decimal is displayed in format "0.00". But after post when modelState is invalid number in displayed in format "0.0000". If model state isvalid, everything goes well. Has anyone encountered anything similar?
If you have javascript modifying the values on textboxes (currency formatting or commas) then you might be getting binding errors because it will behave as a string. Try this:
Create a BindingProperty for decimal values
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
On your global.asax app_start or WebActivator.PostApplicationStartMethod add an entry to register the custom binder:
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
To display dot instead of comma is enough to change the culture to english in every point of the code which is used before the view is called.
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("En");
I'm using Web API within ASP .NET MVC 4 RC, and I have a method that takes a complex object with nullable DateTime properties. I want the values of the input to be read from the query string, so I have something like this:
public class MyCriteria
{
public int? ID { get; set; }
public DateTime? Date { get; set; }
}
[HttpGet]
public IEnumerable<MyResult> Search([FromUri]MyCriteria criteria)
{
// Do stuff here.
}
This works well if I pass a standard date format in the query string such as 01/15/2012:
http://mysite/Search?ID=1&Date=01/15/2012
However, I want to specify a custom format for the DateTime (maybe MMddyyyy)... for example:
http://mysite/Search?ID=1&Date=01152012
Edit:
I've tried to apply a custom model binder, but I haven't had any luck applying it to only DateTime objects. The ModelBinderProvider I've tried looks something like this:
public class DateTimeModelBinderProvider : ModelBinderProvider
{
public override IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(DateTime) || bindingContext.ModelType == typeof(DateTime?))
{
return new DateTimeModelBinder();
}
return null;
}
}
// In the Global.asax
GlobalConfiguration.Configuration.Services.Add(typeof(ModelBinderProvider), new DateTimeModelBinderProvider());
The new model binder provider is created, but GetBinder is only called once (for the complex model parameter, but not for each property within the model). This makes sense, but I would like to find a way to make it to use my DateTimeModelBinder for DateTime properties, while using the default binding for non-DateTime properties. Is there a way to override the default ModelBinder and specify how each property is bound?
Thanks!!!
Consider setting your view-model's Date property to type string
Then either write a utility function to handle the mapping between the viewmodel type and the domain-model type:
public static MyCriteria MapMyCriteriaViewModelToDomain(MyCriteriaViewModel model){
var date = Convert.ToDateTime(model.Date.Substring(0,2) + "/" model.Date.Substring(2,2) + "/" model.Date.Substring(4,2));
return new MyCriteria
{
ID = model.ID,
Date = date
};
}
or use a tool like AutoMapper, like this:
in Global.asax
//if passed as MMDDYYYY:
Mapper.CreateMap<MyCriteriaViewModel, MyCriteria>().
.ForMember(
dest => dest.Date,
opt => opt.MapFrom(src => Convert.ToDateTime(src.Date.Substring(0,2) + "/" src.Date.Substring(2,2) + "/" src.Date.Substring(4,2)))
);
and in the controller:
public ActionResult MyAction(MyCriteriaViewModel model)
{
var myCriteria = Mapper.Map<MyCriteriaViewModel, MyCriteria>(model);
// etc.
}
From this example it might not seem that AutoMapper is providing any added value. It's value comes when you are configuring several or many mappings with objects that generally have more properties than this example. CreateMap will automatically map properties with the same name and type, so it saves lots of typing and it's much DRYer.
How can I force the format of datetime in asp.net mvc 4 ?
In display mode it shows as I want but in edit model it doesn't.
I am using displayfor and editorfor and applyformatineditmode=true with dataformatstring="{0:dd/MM/yyyy}"
What I have tried:
globalization in web.config (both of them) with my culture and uiculture.
modifying the culture and uiculture in application_start()
custom modelbinder for datetime
I have no idea how to force it and I need to input the date as dd/MM/yyyy not the default.
MORE INFO:
my viewmodel is like this
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
in view I use #Html.DisplayFor(m=>m.Birth) but this works as expected (I see the formatting)
and to input the date I use #Html.EditorFor(m=>m.Birth) but if I try and input something like 13/12/2000 is fails with the error that it is not a valid date (12/13/2000 and 2000/12/13 are working as expected but I need dd/MM/yyyy).
The custom modelbinder is called in application_start() b/c I don't know where else.
Using <globalization/> I have tried with culture="ro-RO", uiCulture="ro" and other cultures that would give me dd/MM/yyyy.
I have also tried to set it on a per thread basis in application_start() (there are a lot of examples here, on how to do this)
For all that will read this question:
It seems that Darin Dimitrov's answer will work as long as I don't have client validation.
Another approach is to use custom validation including client side validation.
I'm glad I found this out before recreating the entire application.
Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat] attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407
Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.
Model:
public class MyViewModel
{
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.Birth)
#Html.EditorFor(x => x.Birth)
#Html.ValidationMessageFor(x => x.Birth)
<button type="submit">OK</button>
}
Registration of the custom model binder in Application_Start:
ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());
And the custom model binder itself:
public class MyDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Now, no matter what culture you have setup in your web.config (<globalization> element) or the current thread culture, the custom model binder will use the DisplayFormat attribute's date format when parsing nullable dates.
Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.
My finally working solution:
$(function () {
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
}
});
You have to include before:
#Scripts.Render("~/Scripts/jquery-3.1.1.js")
#Scripts.Render("~/Scripts/jquery.validate.min.js")
#Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
#Scripts.Render("~/Scripts/moment.js")
You can install moment.js using:
Install-Package Moment.js
Thanks Darin,
For me, to be able to post to the create method, It only worked after I modified the BindModel code to :
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
Hope this could help someone else...
We know that MVC returns DateTime for JsonResult in this format: /Date(1240718400000)/, and we know how to parse it in JS.
However, It seems that MVC doesn't accept DateTime parameter being sent in this way. For example, I have the following Action.
[HttpGet]
public ViewResult Detail(BookDetail details) { //... }
The BookDetail class contains a DateTime field named CreateDate, and I passed a JSON object from JS in this format:
{"CreateDate": "/Date(1319144453250)/"}
CreateDate is recognized as null.
If I passed the JSON in this way, it works as expected:
{"CreateDate": "2011-10-10"}
The problem is that I cannot change client side code in an easy way, have to stick to /Date(1319144453250)/ this format. I have to make changes in server side.
How to solve this problem? Is that anything related to ModelBinder?
Thanks so much in advance!
The problem, as you suspected, is a model binding issue.
To work around it, create a custom type, and let's call it JsonDateTime. Because DateTime is a struct, you cannot inherit from it, so create the following class:
public class JsonDateTime
{
public JsonDateTime(DateTime dateTime)
{
_dateTime = dateTime;
}
private DateTime _dateTime;
public DateTime Value
{
get { return _dateTime; }
set { _dateTime = value; }
}
}
Change CreateDate to this type. Next, we need a custom model binder, like so:
public class JsonDateTimeModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();
return new DateTime(Int64.Parse(
value.Substring(6).Replace(")/",String.Empty))); // "borrowed" from skolima's answer
}
}
Then, in Global.asax.cs, in Application_Start, register your custom ModelBinder:
ModelBinders.Binders.Add(typeof(JsonDateTime), new JsonDateTimeModelBinder());
In your model, use this to parse the date:
// property
String CreateDate;
DateTime CreateDateAsDate;
// drop prefix, drop suffix, parse as long and read as ticks
CreateDateAsDate date = new DateTime(Int64.Parse(
CreateDate.Substring(6).Replace(")/",String.Empty)));
I think using custom Model Binder will do the trick. The below model binder class will work on both cases. It will parse all dot net recognizable date string as well as JSON formatted date string. No need to change any existing code.
public class DateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var model = base.BindModel(controllerContext, bindingContext);
if (model == null && (bindingContext.ModelType == typeof(DateTime) || bindingContext.ModelType == typeof(DateTime?)))
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null || String.IsNullOrEmpty(value.AttemptedValue))
model = (bindingContext.ModelType == typeof(DateTime?)) ? null : (object)DateTime.MinValue;
else if (Regex.IsMatch(value.AttemptedValue, #"\/Date\(\d+\)\/"))
model = new DateTime(1970, 1, 1).AddMilliseconds(Int64.Parse(value.AttemptedValue.Substring(6).Replace(")/", String.Empty))).ToLocalTime();
//else //Any other format
}
return model;
}
}
Configure Model Binder in Application_Start of Global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//Your Existing Code....
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());
}
}
Vote If it helps
Asp.net-MVC now allows for implicit binding of DateTime objects. I have an action along the lines of
public ActionResult DoSomething(DateTime startDate)
{
...
}
This successfully converts a string from an ajax call into a DateTime. However, we use the date format dd/MM/yyyy; MVC is converting to MM/dd/yyyy.
For example, submitting a call to the action with a string '09/02/2009' results in a DateTime of '02/09/2009 00:00:00', or September 2nd in our local settings.
I don't want to roll my own model binder for the sake of a date format. But it seems needless to have to change the action to accept a string and then use DateTime.Parse if MVC is capable of doing this for me.
Is there any way to alter the date format used in the default model binder for DateTime? Shouldn't the default model binder use your localisation settings anyway?
I've just found the answer to this with some more exhaustive googling:
Melvyn Harbour has a thorough explanation of why MVC works with dates the way it does, and how you can override this if necessary:
http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx
When looking for the value to parse, the framework looks in a specific order namely:
RouteData (not shown above)
URI query string
Request form
Only the last of these will be culture aware however. There is a very good reason for this, from a localization perspective. Imagine that I have written a web application showing airline flight information that I publish online. I look up flights on a certain date by clicking on a link for that day (perhaps something like http://www.melsflighttimes.com/Flights/2008-11-21), and then want to email that link to my colleague in the US. The only way that we could guarantee that we will both be looking at the same page of data is if the InvariantCulture is used. By contrast, if I'm using a form to book my flight, everything is happening in a tight cycle. The data can respect the CurrentCulture when it is written to the form, and so needs to respect it when coming back from the form.
I would globally set your cultures. ModelBinder pick that up!
<system.web>
<globalization uiCulture="en-AU" culture="en-AU" />
Or you just change this for this page.
But globally in web.config I think is better
I've been having the same issue with short date format binding to DateTime model properties. After looking at many different examples (not only concerning DateTime) I put together the follwing:
using System;
using System.Globalization;
using System.Web.Mvc;
namespace YourNamespaceHere
{
public class CustomDateBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext", "controllerContext is null.");
if (bindingContext == null)
throw new ArgumentNullException("bindingContext", "bindingContext is null.");
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null)
throw new ArgumentNullException(bindingContext.ModelName);
CultureInfo cultureInf = (CultureInfo)CultureInfo.CurrentCulture.Clone();
cultureInf.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
try
{
var date = value.ConvertTo(typeof(DateTime), cultureInf);
return date;
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
return null;
}
}
}
public class NullableCustomDateBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext", "controllerContext is null.");
if (bindingContext == null)
throw new ArgumentNullException("bindingContext", "bindingContext is null.");
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null) return null;
CultureInfo cultureInf = (CultureInfo)CultureInfo.CurrentCulture.Clone();
cultureInf.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
try
{
var date = value.ConvertTo(typeof(DateTime), cultureInf);
return date;
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
return null;
}
}
}
}
To keep with the way that routes etc are regiseterd in the Global ASAX file I also added a new sytatic class to the App_Start folder of my MVC4 project named CustomModelBinderConfig:
using System;
using System.Web.Mvc;
namespace YourNamespaceHere
{
public static class CustomModelBindersConfig
{
public static void RegisterCustomModelBinders()
{
ModelBinders.Binders.Add(typeof(DateTime), new CustomModelBinders.CustomDateBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new CustomModelBinders.NullableCustomDateBinder());
}
}
}
I then just call the static RegisterCustomModelBinders from my Global ASASX Application_Start like this:
protected void Application_Start()
{
/* bla blah bla the usual stuff and then */
CustomModelBindersConfig.RegisterCustomModelBinders();
}
An important note here is that if you write a DateTime value to a hiddenfield like this:
#Html.HiddenFor(model => model.SomeDate) // a DateTime property
#Html.Hiddenfor(model => model) // a model that is of type DateTime
I did that and the actual value on the page was in the format "MM/dd/yyyy hh:mm:ss tt" instead of "dd/MM/yyyy hh:mm:ss tt" like I wanted. This caused my model validation to either fail or return the wrong date (obviously swapping the day and month values around).
After a lot of head scratching and failed attempts the solution was to set the culture info for every request by doing this in the Global.ASAX:
protected void Application_BeginRequest()
{
CultureInfo cInf = new CultureInfo("en-ZA", false);
// NOTE: change the culture name en-ZA to whatever culture suits your needs
cInf.DateTimeFormat.DateSeparator = "/";
cInf.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
cInf.DateTimeFormat.LongDatePattern = "dd/MM/yyyy hh:mm:ss tt";
System.Threading.Thread.CurrentThread.CurrentCulture = cInf;
System.Threading.Thread.CurrentThread.CurrentUICulture = cInf;
}
It won't work if you stick it in Application_Start or even Session_Start since that assigns it to the current thread for the session. As you well know, web applications are stateless so the thread that serviced your request previously is ot the same thread serviceing your current request hence your culture info has gone to the great GC in the digital sky.
Thanks go to:
Ivan Zlatev - http://ivanz.com/2010/11/03/custom-model-binding-using-imodelbinder-in-asp-net-mvc-two-gotchas/
garik - https://stackoverflow.com/a/2468447/578208
Dmitry - https://stackoverflow.com/a/11903896/578208
It going to be slightly different in MVC 3.
Suppose we have a controller and a view with Get method
public ActionResult DoSomething(DateTime dateTime)
{
return View();
}
We should add ModelBinder
public class DateTimeBinder : IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
DateTime dateTime;
if (DateTime.TryParse(controllerContext.HttpContext.Request.QueryString["dateTime"], CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dateTime))
return dateTime;
//else
return new DateTime();//or another appropriate default ;
}
#endregion
}
and the command in Application_Start() of Global.asax
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
It is also worth noting that even without creating your own model binder multiple different formats may be parsable.
For instance in the US all the following strings are equivalent and automatically get bound to the same DateTime value:
/company/press/may%2001%202008
/company/press/2008-05-01
/company/press/05-01-2008
I'd strongly suggest using yyyy-mm-dd because its a lot more portable. You really dont want to deal with handling multiple localized formats. If someone books a flight on 1st May instead of 5th January you're going to have big issues!
NB: I'm not clear exaclty if yyyy-mm-dd is universally parsed in all cultures so maybe someone who knows can add a comment.
I set the below config on my MVC4 and it works like a charm
<globalization uiCulture="auto" culture="auto" />
Try to use toISOString(). It returns string in ISO8601 format.
GET method
javascript
$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
console.log(result);
});
c#
[HttpGet]
public JsonResult DoGet(DateTime date)
{
return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}
POST method
javascript
$.post('/example/do', { date: date.toISOString() }, function (result) {
console.log(result);
});
c#
[HttpPost]
public JsonResult Do(DateTime date)
{
return Json(date.ToString());
}
public class DateTimeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.RequestType == "GET")
{
foreach (var parameter in filterContext.ActionParameters)
{
var properties = parameter.Value.GetType().GetProperties();
foreach (var property in properties)
{
Type type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
if (property.PropertyType == typeof(System.DateTime) || property.PropertyType == typeof(DateTime?))
{
DateTime dateTime;
if (DateTime.TryParse(filterContext.HttpContext.Request.QueryString[property.Name], CultureInfo.CurrentUICulture, DateTimeStyles.None, out dateTime))
property.SetValue(parameter.Value, dateTime,null);
}
}
}
}
}
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var str = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
if (string.IsNullOrEmpty(str)) return null;
var date = DateTime.ParseExact(str, "dd.MM.yyyy", null);
return date;
}
I set CurrentCulture and CurrentUICulture my custom base controller
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");
}