我有用于 ModelBinding 的 bindingContext.ValueProvider.GetValue(bindingContext.ModelName) 并且它返回 null,但是如果我使用 bindingContext.ValueProvider.GetValue("id") 则返回正确的记录。任何想法缺少什么?我应该以某种方式注册模型类吗?
public class EntityModelBinder<TEntity>: IModelBinder where TEntity : Entity
{
private readonly IUnitOfWork unitOfWork;
public EntityModelBinder(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var id = Guid.Parse(value.AttemptedValue);
var entity = ((IGenericRepository<TEntity>)unitOfWork.GetRepository(typeof(TEntity))).GetByID(id);
return entity;
}
}
控制器调用是“比尔”是我的实体类之一,它是 UnitOfWork 的一部分:
public ActionResult Edit(Bill bill)
{
var model = Mapper.Map<Bill, BillEditModel>(bill);
return View("Edit",model);
}