0

I have the following struct:

public struct DataRange
{
    public DateTime BeginDate {get;set;}
    public DateTime EndDate {get;set;}
}

This struct is used on many actions of my asp.net mvc 5 app.

I am using a custom input (daterangepicker) and i want to bind the custom string value of the input to my custom datatype just one time and use it along my app.

E.g:

public class FindSalesByDateViewModel
{
    public DateRange Interval {get; set;}
}

public class SalesController : Controller
{
    public ActionResult Index(FindSalesByDateViewModel model)
    {
        //Access the model.Interval without parse the string value always.
    }
}

I'm a beginner on mvc development. I found the following solutions that are not very attractive, is there any other way to accomplish this?

Solution 1

Solution 2

EDIT

The custom input value that comes from view is: "08/10/2016 - 15/10/2016"

Community
  • 1
  • 1
Vinicius Gonçalves
  • 2,514
  • 1
  • 29
  • 54

1 Answers1

1

You can register your custom model binder in Application_Start:

ModelBinders.Binders[typeof(DateTime)] = new YourCustomModelBinder();
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Hi! Tks for reply, can you post a sample code/documentation link please? – Vinicius Gonçalves Oct 08 '16 at 20:26
  • 1
    Hi, you're welcome. Take a look at this: [Globalization: Model binding DateTimes with ASP.Net MVC](http://www.hackered.co.uk/articles/globalization-model-binding-datetimes-with-asp-net-mvc) or this one: [Custom Date Formats and the MVC Model Binder](https://blog.greatrexpectations.com/2013/01/10/custom-date-formats-and-the-mvc-model-binder/) or this one: [Splitting DateTime - Unit Testing ASP.NET MVC Custom Model Binders](http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx) – Reza Aghaei Oct 08 '16 at 20:30
  • On my scenario, the value cames as string, how can i register in this case? – Vinicius Gonçalves Oct 08 '16 at 20:41
  • All values come as string. But the type which you want to bind to it, is the type which you should use in `ModelBinders.Binders[typeof(DateTime)] `. – Reza Aghaei Oct 08 '16 at 20:43
  • Also you can post two values `BeginDate` and `EndDate` with suitable prefix. For example if the Action is `SomeAction(DataRange model)` no prefix is needed. If you have a Model like `public class MyModel { public DataRange Range {get;set;}}` then the action should be `SomeAction(MyModel model)` and the posted values should be `model.BeginDate` and `model.EndDate`. Putting the prefix is the job of `Html.Range` or `Html.RangeFor` helper method which you created. – Reza Aghaei Oct 08 '16 at 21:07
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/125248/discussion-between-vinicius-goncalves-and-reza-aghaei). – Vinicius Gonçalves Oct 08 '16 at 21:52
  • Chat doesn't have notifications. Leave a comment instead and use chat when we both are online :) – Reza Aghaei Oct 08 '16 at 22:37