MVC3 - UpdateModel... how to change incoming data?

269 views Asked by At

UpdateModel fails because arcm.Notes was null coming into this method and I want it to be an empty string.

Maybe I need to refresh the ValueProvider (?) after setting Notes to "", so I can use 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

There are 1 answers

0
Adam Tuliper On BEST ANSWER

This is the default behavior I believe since MVC2. note one workaround here:

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);
    }
}

And register the binder


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