簡體   English   中英

使用MongoDB時,ModelState.IsValid包含錯誤

[英]ModelState.IsValid contains errors when using MongoDB

我正在嘗試使用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對象。 但我無法弄清楚如何解決這個問題,任何想法?

對於任何尋找這個答案的人來說,從這篇文章中它完美地運作: 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);
    }
}

然后在app start中注冊:

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

問題是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)

似乎你需要編寫自己的自定義類型轉換器。
看看這個討論: ObjectId Type Converter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM