asp.net mvc - MVC UpdateModel when the names don't match up -


Assume that you have a model that looks like this:

   Public class MyClass {public string name {get; Set; } Public Datetime Mediate (Receive); Set; }}  

Visual Studio gives you the default editing template is MyDate is a plain text box for the property is all well and good, but says That you need to split up in this month / day / year components, and look like your appearance:

   

When it is submitted, call will not work on UpdateModel , because there is no definition for MyDate-Month . Is there a way to connect a custom binder to tackle the situation in this way, or HTML inputs are different names (for whatever reasons)?

inject a hidden input uses JavaScript for a workaround I found a form before submitting the fields combined and named properly, but it seems wrong .

After the

I will suggest a custom model binder to you:

  System Use; Using System.Globalization; Using System.Web.Mvc; Override public square MyClassBinder: DefaultModelBinder {protected object CreateModel (ControllerContext controllerContext, ModelBindingContext bindingContext, type modelType) {var model = (MyClass) base.CreateModel (controllerContext, bindingContext, modelType); Var day = binding content box. Value provider ["predetermined"]; Var months = binding content box. Value provider ["midnight-month"]; Var year = binding content. Value provider ["mid-year"]; Var dateStr = String.Format ( "{0} / {1} / {2}", month.AttemptedValue, day.AttemptedValue, year.AttemptedValue); Date time date; If (DateTime.TryParseExact (dateStr, "mm / dd / yyyy", null, DateTimeStyles.None, out of date)) {model.MyDate = date; } Else {bindingContext.ModelState.AddModelError ("MyDate", "MyDate's Invalid Format"); } BindingContext.ModelState.SetModelValue ("MyDate-Day", Day); Binding Contains ModelState. Setmodel value ("maidat-month", month); Binding Contains ModelState. Satmold Value ("Mite-Year", Year); Return model; }}  

It simplifies your controller action:

  [AcceptVerbs (Acteepivirbskpost)] public action results Mayakshn (Maiklas Maiklas) {if (ModelState .IsValid) {Return View (myClass); } // do something with myClass Return; Redirect ToAction ("Success"); }  

and register the binders in Global. Ax:

  Protected Zero application_Start () {RegisterRout (RouteTable.Rout); Modalbinders.binders.ed (Typf (Myclass), new MyScassBender ()); }  

Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -