加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – ModelState.IsValid在使用MongoDB时包含错误

发布时间:2020-12-16 00:21:40 所属栏目:百科 来源:网络整理
导读:我正在尝试使用ASP.NET MVC 4和MongoDB创建一个基本的电影数据库.我的问题出在我的MovieController的POST Update方法中. [HttpPost] public ActionResult Update(Movie movie) { if (ModelState.IsValid) { _movies.Edit(movie); return RedirectToAction("I
我正在尝试使用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();
    }

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

和模型中的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; }
    }
}

编辑:解决方案
我将[ScaffoldColumn(false)]添加到Id中,以便浏览器不会尝试渲染它.但是我仍然需要实现Mihai提供的解决方案才能传递正确的ID.

我假设问题是在视图中引起的,因为它试图发送字符串而不是ObjectId对象.但我无法弄清楚如何解决这个问题,任何想法?

解决方法

问题是MVC不知道如何将您的Id转换为ObjectId类型.它只将其视为字符串.

您必须为您的方法使用自定义绑定器.
看看这个链接http://www.dotnetcurry.com/ShowArticle.aspx?ID=584

看看这个

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

并更改您的Update方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读