简体   繁体   English

使用MongoDB时,ModelState.IsValid包含错误

[英]ModelState.IsValid contains errors when using MongoDB

I'm trying to create a basic movie database using ASP.NET MVC 4 and MongoDB. 我正在尝试使用ASP.NET MVC 4和MongoDB创建一个基本的电影数据库。 My problem is in the POST Update method of my MovieController. 我的问题出在我的MovieController的POST Update方法中。

[HttpPost]
    public ActionResult Update(Movie movie)
    {
        if (ModelState.IsValid)
        {

            _movies.Edit(movie);

            return RedirectToAction("Index");
        }

        return View();
    }

The ModelState contains an error for the movie's Id field (which is an ObjectId object) and throws the following exception: 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

This is the Update view: 这是更新视图:

@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>
}

And the Movie class in Models: 和模型中的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; }
    }
}

EDIT: Solution I added the [ScaffoldColumn(false)] to the Id so that the browser does not attempt to render it. 编辑:解决方案我将[ScaffoldColumn(false)]添加到Id,以便浏览器不会尝试渲染它。 However I still needed to implement the solution provided by Mihai in order to pass the correct Id. 但是我仍然需要实现Mihai提供的解决方案才能传递正确的ID。

I'm assuming that the problem is being caused in the view because it tries to send a string instead of an ObjectId object. 我假设问题是在视图中引起的,因为它试图发送字符串而不是ObjectId对象。 But I cannot figure out how to fix this, any ideas? 但我无法弄清楚如何解决这个问题,任何想法?

For anyone else looking for this answer, from this post and it works perfectly : http://www.joe-stevens.com/2011/06/12/model-binding-mongodb-objectid-with-asp-net-mvc/ 对于任何寻找这个答案的人来说,从这篇文章中它完美地运作: http//www.joe-stevens.com/2011/06/12/model-binding-mongodb-objectid-with-asp-net-mvc/

Create a Model Binder : 创建模型绑定器:

public class ObjectIdBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        return new ObjectId(result.AttemptedValue);
    }
}

Then register in app start : 然后在app start中注册:

protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdBinder());
}

The problem is that MVC doesn't know how to convert your Id to ObjectId type. 问题是MVC不知道如何将您的Id转换为ObjectId类型。 It only sees it as string. 它只将其视为字符串。

You'll have to use a custom binder for your method. 您必须为您的方法使用自定义绑定器。 Have a look at this link http://www.dotnetcurry.com/ShowArticle.aspx?ID=584 看看这个链接http://www.dotnetcurry.com/ShowArticle.aspx?ID=584

Have a look at this 看看这个

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;
    }
}

And change your Update method as so 并更改您的Update方法

public ActionResult Update([ModelBinder(typeof(MovieModelBinder))] Movie movie)

Seems you need to writer your own custom type converter. 似乎你需要编写自己的自定义类型转换器。
Check out this discussion: ObjectId Type Converter 看看这个讨论: ObjectId Type Converter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM