2011-11-01 24 views
0

UpdateModel失败,因为arcm.Notes进入此方法为null,我希望它是一个空字符串。MVC3 - UpdateModel ...如何更改传入数据?

也许我需要在将Notes设置为“”后刷新ValueProvider(?),所以我可以使用UpdateModel。

public ActionResult Edit1(Guid id, ActivityResponseConsumerMobile arcm) { 
     if (arcm.Notes == null) 
      arcm.Notes = ""; 

     if (!ModelState.IsValid) { 
      SetupDropDowns(); 
      return View(arcm); 
     } 

     ActivityResponseConsumerMobile arcmDb = uow.ActivityResponseConsumerMobiles.Single(a => a.Id == id); 
     try { 
      UpdateModel(arcmDb, null, null, new[] { "Id" }); 

回答

1

这是我相信自从MVC2以来的默认行为。 注意到一个解决办法在这里:

http://brianreiter.org/2010/09/16/asp-net-mvc-2-0-undocumented-model-string-property-breaking-change/

 

public sealed class EmptyStringModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     bindingContext.ModelMetadata.ConvertEmptyStringToNull = false; 
     return base.BindModel(controllerContext, bindingContext); 
    } 
} 
 

并注册粘结剂

 

protected void Application_Start() 
{ 
    ModelBinders.Binders.DefaultBinder = new EmptyStringModelBinder(); 
    RegisterRoutes(RouteTable.Routes); 
}