1

我正在使用模型绑定器来操作一些数据。我想从 .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
}
4

1 回答 1

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() 中放置一个断点并观察值。

于 2013-10-04T21:17:45.460 回答