ASP.NET MVC datetime culture issue when passing value back to controller

前端 未结 7 1392
既然无缘
既然无缘 2020-12-05 18:32

How can i tell my controller/model what kind of culture it should expect for parsing a datetime?

I was using some of this post to implement jquery d

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 19:28

    You can create a Binder extension to handle the date in the culture format.

    This is a sample I wrote to handle the same problem with Decimal type, hope you get the idea

     public class DecimalModelBinder : IModelBinder
     {
       public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
       {
         ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
         ModelState modelState = new ModelState { Value = valueResult };
         object actualValue = null;
         try
         {
           actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
         }
         catch (FormatException e)
         {
           modelState.Errors.Add(e);
         }
    
         bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
         return actualValue;
      }
    }
    

    Update

    To use it simply declare the binder in Global.asax like this

    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();
      RegisterGlobalFilters(GlobalFilters.Filters);
      RegisterRoutes(RouteTable.Routes);
    
      //HERE you tell the framework how to handle decimal values
      ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    
      DependencyResolver.SetResolver(new ETAutofacDependencyResolver());
    }
    

    Then when the modelbinder has to do some work, it will know automatically what to do. For example, this is an action with a model containing some properties of type decimal. I simply do nothing

    [HttpPost]
    public ActionResult Edit(int id, MyViewModel viewModel)
    {
      if (ModelState.IsValid)
      {
        try
        {
          var model = new MyDomainModelEntity();
          model.DecimalValue = viewModel.DecimalValue;
          repository.Save(model);
          return RedirectToAction("Index");
        }
        catch (RulesException ex)
        {
          ex.CopyTo(ModelState);
        }
        catch
        {
          ModelState.AddModelError("", "My generic error message");
        }
      }
      return View(model);
    }
    

提交回复
热议问题