【发布时间】:2014-08-14 09:26:26
【问题描述】:
我正在尝试使用自定义模型绑定器将记录添加到我的数据库中
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>();
}
}
【问题讨论】:
-
@nvoigt 谢谢,我明白了那个帖子。Category 给了我 null 值,但我不明白为什么它给我 null
-
也发布您的观点,我也不确定您如何使用提交按钮提交数据?阿贾克斯?等等,也许您需要在视图
@Html.HiddenFieldFor(m => m.Category.CategoryID)中创建隐藏字段,我只是在信息有限的情况下在这里猜测 -
@Yuliam 我的视图是 jqgrid,所以没有任何自定义代码,只有一个链接到我的控制器的 url
标签: c# asp.net-mvc entity-framework ninject custom-model-binder