IModelBinder - 如何获取进行更改的默认绑定值

时间:2013-10-04 19:35:55

标签: asp.net asp.net-mvc-4 model-binding

我正在使用模型绑定器来操作一些数据。我想从.net获取绑定模型并操纵它。

   public class FilePointerBinder : IModelBinder
    {
        public new object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
              //MyCustomSubModel  value = new MyCustomSubModel();//THIS IS NOT GOOD
              MyCustomSubModel value = (MyCustomSubModel)GetTheDefaultValueFromSomeWhere();
              value.Id = 0;
              return value;
        }
    }

修改

public class User{
   public int Id{get;set;}
   public FilePointer File{get;set;}// this is null
}

1 个答案:

答案 0 :(得分:0)

您可以这样做:

public class FilePointerBinder : IModelBinder
{
    public new object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue("FilePointer");
        if(value != null)
        {
            //Object is not null
           return value;
        }
        else
        {
           return new FilePointer();//Filepointer with default value                
        }

    }
}

编辑:假设你在Global.asax.cs中有这个,Application_Start():

ModelBinders.Binders.Add(typeof(FilePointer), new FilePointerBinder());

您可以在BindModel()中放置一个断点并观察该值。