カスタム モデル バインダーを使用してデータベースにレコードを追加しようとしています
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 instance of object エラーが表示されます
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>();
}
}