ModelBindingContext.ValueProvider.GetValue(bindingContext.ModelName) returns null

最后都变了- 提交于 2019-12-11 02:43:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!