Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would suggest you a custom model binder:</p> <pre><code>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; } } </code></pre> <p>This simplifies your controller action to:</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult MyAction(MyClass myClass) { if (!ModelState.IsValid) { return View(myClass); } // Do something with myClass return RedirectToAction("success"); } </code></pre> <p>And register the binder in Global.asax:</p> <pre><code>protected void Application_Start() { RegisterRoutes(RouteTable.Routes); ModelBinders.Binders.Add(typeof(MyClass), new MyClassBinder()); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload