C# ModelState.IsValid在使用MongoDB时包含错误
我正在尝试使用ASP.NETMVC4和MongoDB创建一个基本的电影数据库。我的问题是我的MovieController的后期更新方法C# ModelState.IsValid在使用MongoDB时包含错误,c#,asp.net-mvc,mongodb,asp.net-mvc-4,modelstate,C#,Asp.net Mvc,Mongodb,Asp.net Mvc 4,Modelstate,我正在尝试使用ASP.NETMVC4和MongoDB创建一个基本的电影数据库。我的问题是我的MovieController的后期更新方法 [HttpPost] public ActionResult Update(Movie movie) { if (ModelState.IsValid) { _movies.Edit(movie); return RedirectToAction("Index"
[HttpPost]
public ActionResult Update(Movie movie)
{
if (ModelState.IsValid)
{
_movies.Edit(movie);
return RedirectToAction("Index");
}
return View();
}
ModelState包含电影Id字段(是ObjectId对象)的错误,并引发以下异常:
{System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'MongoDB.Bson.ObjectId' failed because no type converter can convert between these types
这是更新视图:
@model MVCMovie.Models.Movie
@{
ViewBag.Title = "Update";
}
<h2>Update</h2>
@using (Html.BeginForm())
{
@Html.HiddenFor(m => m.Id);
@Html.EditorForModel()
<p>
<input type="submit" value="Update" />
</p>
}
编辑:解决方案
我将[ScaffoldColumn(false)]添加到Id中,这样浏览器就不会试图呈现它。但是,为了传递正确的Id,我仍然需要实现Mihai提供的解决方案
我假设问题是在视图中引起的,因为它试图发送字符串而不是ObjectId对象。但是我不知道如何解决这个问题,有什么想法吗?问题是MVC不知道如何将您的Id转换为ObjectId类型。它只将其视为字符串 您必须为您的方法使用自定义活页夹。 看看这个链接 看看这个
public class MovieModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var modelBinder = new DefaultModelBinder();
var movie = modelBinder.BindModel(controllerContext, bindingContext) as Movie;
var id = controllerContext.HttpContext.Request.Form["Id"];
if (movie != null)
{
movie.Id = new ObjectId(id);
return movie ;
}
return null;
}
}
并更改您的更新方法
public ActionResult Update([ModelBinder(typeof(MovieModelBinder))] Movie movie)
似乎您需要编写自己的自定义类型转换器。
查看以下讨论:
对于其他正在寻找此答案的人,请参阅本帖,它可以完美地工作: 创建模型绑定器:
public class ObjectIdBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return new ObjectId(result.AttemptedValue);
}
}
然后在应用程序启动中注册:
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdBinder());
}
这是一个评论,不是回答抱歉等待,我正在尝试。这还没有完全奏效,但我认为你走对了方向。发送到该方法的电影现在具有正确的Id(ObjectId),但ModelState仍然给我相同的错误。我会继续调查的,谢谢你的帮助。。您可以用自己的验证逻辑替换ModelState.IsValid,但我假设您想使用MVC属性:)我喜欢这样,因为您不需要在所有控制器上都使用那种凌乱的[ModelBinder(typeof(MovieModelBinder))。投票赞成Joe Stevens博客的链接。这就像买的一样。
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdBinder());
}