2011-11-01 25 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); 
}