Vinicius Gonçalves
Vinicius Gonçalves

Reputation: 2724

Custom parse value for ViewModel property (Custom Bind)

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"

Upvotes: 0

Views: 271

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125187

You can register your custom model binder in Application_Start:

ModelBinders.Binders[typeof(DateTime)] = new YourCustomModelBinder();

Upvotes: 1

Related Questions