forum

Home / DeveloperSection / Forums / ModelState.IsValid contains errors when using MongoDB

ModelState.IsValid contains errors when using MongoDB

Anonymous User 3398 29-Mar-2014

I'm trying to create a basic movie database using ASP.NET MVC 4 and MongoDB. My problem is in the POST Update method of my MovieController.                                                                                                                               

[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:

 {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:

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

I'm assuming that the problem is being caused in the view because it tries to send a string instead of an ObjectId object. But I cannot figure out how to fix this, any ideas?


Updated on 29-Mar-2014
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By