Home > DeveloperSection > Forums > ModelState.IsValid contains errors when using MongoDB
Simons Hood
Simons Hood

Total Post:70

Posted on    March-29-2014 6:48 AM


 1 Reply(s)
 1916  View(s)
Rate this:

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.



    public ActionResult Update(Movie movie)


        if (ModelState.IsValid)



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



@using (Html.BeginForm())


    @Html.HiddenFor(m => m.Id);



        <input type="submit" value="Update" />



And the Movie class in Models:

namespace MVCMovie.Models


    public class Movie



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


        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?

Pravesh Singh

Total Post:411

Posted on    March-29-2014 7:09 AM

Hi Samuel,

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

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

Don't want to miss updates? Please click the below button!

Follow MindStick