问题
I have bindingContext.ValueProvider.GetValue(bindingContext.ModelName) for ModelBinding and it returns null, but if I use bindingContext.ValueProvider.GetValue("id") is returns the correct record. Any Idea what's missing? Am I supposed to register the model class somehow?
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;
}
}
And Controller Call is "Bill" is one of my Entity Classes, and it's part of the UnitOfWork:
public ActionResult Edit(Bill bill)
{
var model = Mapper.Map<Bill, BillEditModel>(bill);
return View("Edit",model);
}
回答1:
I am not an expert on mvc, but I have an idea about your issue. I am assuming that you are trying to get a Bill entity from your unit of work. Your action method defines the parameter Bill bill
. This means that MVC will set bindingContext.ModelName
to "bill", not "id".
Instead of trying to get Bill entity through model binding, I suggest using your unit of work within the controller. So the Edit action could be like
public ActionResult Edit(Guid id)
{
Bill bill = _unitOfWork.GetByID(id);
}
and your Controller constructor might be like:
public MyController(IUnitOfWork uow) {
_unitOfWork = uow;
}
This is assuming that you are using DI.
I think, using the model binder for getting entities from repository could be dangerous. Unless your GetByID method throws an exception, MVC will continue searching for Bill entity in request data. Imagine a scenario, where user posts a new entity that does not exist in your repository. Your controller will have to do some extra work to check whether this entity really exists in your repository.
You are better off using your unit of work within the controller.
来源:https://stackoverflow.com/questions/14106447/modelbindingcontext-valueprovider-getvaluebindingcontext-modelname-returns-nul