1

我正在尝试使用自定义模型绑定器将记录添加到我的数据库中

public class PostModelBinder: DefaultModelBinder
{
    private IBlogRepository repository;

    public PostModelBinder(IBlogRepository repo)
    {
        repository = repo;
    }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var post = (Post)base.BindModel(controllerContext, bindingContext);

        if (post.Category != null)
            post.Category = repository.Category(post.Category.CategoryID);

        var tags = bindingContext.ValueProvider.GetValue("Tags").AttemptedValue.Split(',');

        if (tags.Length > 0)
        {
            post.Tags = new List<Tag>();

            foreach (var tag in tags)
            {
                post.Tags.Add(repository.Tag(int.Parse(tag.Trim())));
            }
        }

        return post;
    }
}

当我尝试提交我的记录时,我得到 Object reference not set to an instance of an object error on this line

post.Category = repository.Category(post.Category.CategoryID);

我不确定它为什么会导致此错误。

这是我在 Global.asax.cs 中设置模型绑定器的方法

//model binder
var repository = DependencyResolver.Current.GetService<IBlogRepository>();
ModelBinders.Binders.Add(typeof(Post), new PostModelBinder(repository));

我的存储库

public Category Category(int id)
{
    return context.Categories.FirstOrDefault(c => c.CategoryID == id);
}

和我的控制器动作

[HttpPost]
public ContentResult AddPost(Post post)
{
        string json;

        ModelState.Clear();

        if (TryValidateModel(post))
        {
            var id = repository.AddPost(post);

            json = JsonConvert.SerializeObject(new
            {
                id = id,
                success = true,
                message = "Post added successfully."
            });
        }
        else
        {
            json = JsonConvert.SerializeObject(new
            {
                id = 0,
                success = false,
                message = "Failed to add the post."
            });
        }
        return Content(json, "application/json");
}

这是我正在使用的工厂:

public class NinjectControllerFactory: DefaultControllerFactory
{
    private IKernel ninjectKernel;

    public NinjectControllerFactory()
    {
        ninjectKernel = new StandardKernel();
        AddBindings();
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return controllerType == null
            ? null
            : (IController)ninjectKernel.Get(controllerType);
    }

    private void AddBindings()
    {
        ninjectKernel.Bind<IBlogRepository>().To<EFBlogRepository>();
        ninjectKernel.Bind<IAuthProvider>().To<FormsAuthProvider>();
    }
}
4

2 回答 2

2

我解决了这个问题。

首先,我用 ninject 依赖解析器切换了 ninject 控制器工厂。

使用依赖解析器后,我收到另一个错误消息“IEntityChangeTracker 的多个实例无法引用实体对象”请参见此处

所以我在那个问题中尝试了建议的答案,但仍然没有希望(但这最终也帮助了我)。然后我在这篇文章part-5-creating-a-post的评论部分问了另一个问题,并意识到有一个用于依赖注入的 ninject mvc 扩展,我安装了该扩展,在其中添加了我的绑定并删除了我自己的依赖解析器,在先前答案的帮助下,我添加了“InRequestScope()”(为此,您必须拥有 Ninject.Web.Common)并且它起作用了。

所以在 App_Start 文件夹下的 NinjectWebCommon.cs 中:

kernel.Bind<IBlogRepository>().To<EFBlogRepository>().InRequestScope();
于 2014-08-14T01:26:26.597 回答
1

这是一个模型绑定问题。该Category对象未与 POST 值正确绑定。使用 Firebug 或一些工具,看看是否CategoryID是从 jqGrid 发布的。

于 2014-08-12T09:23:12.853 回答