There are two @Html.DropDownListFor() , one of which involves the choice of a date, and the second - the time of the event. Tell me, please, is it possible with razor to transfer two values ​​as one line to the controller from the view? Those. the result is a single format variable in the controller, for example, "MM / dd / yyyy / HH / mm / ss", while the date: "MM / dd / yyyy" and time: "HH / mm are taken from the individual DropDownListFor() " / ss ".

Is it possible to put these lines together and transfer to the controller method as one line?

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

You need a custom model binding. The model binding mechanism in asp.net is smart enough for simple and for most complex models, but in such cases it is powerless. Here comes the opportunity to create your own model anchors. To do this, you need to create a class that implements the IModelBinder interface. It is easier to do this by inheriting from the DefaultModelBinder class. Like that:

 public class DateTimeModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var request = controllerContext.HttpContext.Request; var date = DateTime.Parse(request.Form.Get("date")); var time = TimeSpan.Parse(request.Form.Get("time")); date = DateTime.Today.Add(time); return date; } } 

and then apply to indicate this class as a model binder for your parameter. It is unlikely that you want to customize the model in this way everywhere in your project, so you should do it with the attribute for the parameter of your method. Like that:

 ActionResult MyAction([ModelBinder(typeof(DateTimeModelBinder))] DateTime arg) 
  • DreamChild, thanks for the reply. It seems that this is just what you need. The only thing, if you will allow me, I wanted to clarify, is it possible to use such a method for the case when a model is transmitted to the controller and DateTime arg in this case is just one of the fields? - Egor
  • in this case, you need to add the corresponding attribute for the field of this type in the model itself. Or, if there is a need, write a class to bind the entire model, including the field with the date - DreamChild
  • Everything seems understood. Thank you very much - Egor