Mat*_*att 3 c# asp.net-mvc modelstate mongodb asp.net-mvc-4
我正在尝试使用ASP.NET MVC 4和MongoDB创建一个基本的电影数据库.我的问题出在我的MovieController的POST Update方法中.
[HttpPost]
public ActionResult Update(Movie movie)
{
if (ModelState.IsValid)
{
_movies.Edit(movie);
return RedirectToAction("Index");
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
这是更新视图:
@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>
}
Run Code Online (Sandbox Code Playgroud)
和模型中的Movie类:
namespace MVCMovie.Models
{
public class Movie
{
[BsonId]
public ObjectId Id { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
[ScaffoldColumn(false)]
public DateTime TimeAdded { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:解决方案我将[ScaffoldColumn(false)]添加到Id,以便浏览器不会尝试渲染它.但是我仍然需要实现Mihai提供的解决方案才能传递正确的ID.
我假设问题是在视图中引起的,因为它试图发送字符串而不是ObjectId对象.但我无法弄清楚如何解决这个问题,任何想法?
对于任何寻找这个答案的人来说,从这篇文章中它完美地运作:http://www.joe-stevens.com/2011/06/12/model-binding-mongodb-objectid-with-asp-net-mvc/
创建模型绑定器:
public class ObjectIdBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return new ObjectId(result.AttemptedValue);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在app start中注册:
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdBinder());
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
929 次 |
最近记录: |