0

What is the design paradigm to use when one wants to fill in some model values from the 'backend'? e.g. I have movies DB; users can create movies. I want to record who created a movie, CreateOn, LastModified. My model has UserId, CreatedOn, LastModified, ... (name, genre etc). The default view generated has all these fields; I removed CreatedOn, LastModified, UserId from create view; now when things come back to Create function in controller, the model is invalid. I cleared the model errors via Clear function, then filled in these 3 values in the controller. But then this is not right; the Clear clears off any other validation errors as well.

public ActionResult Create([Bind(Include = "Name,Description,Genre")] Movie movie)
{
    ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

    ModelState.Clear();
    movie.UserId = user.Id;
    movie.CreatedOn = DateTime.UtcNow;
    movie.LastModified = DateTime.UtcNow;


    if (ModelState.IsValid)
    {
        db.Movies.Add(movie);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(movie);
} 
Amit
  • 1,836
  • 15
  • 24
  • Can you show your model as well as the error you would get? There could be a lot of things going on: missing a required field, mapping properties before checking `ModelState.IsValid` (one of the properties may *not* be valid), etc. – Drew Kennedy Jul 10 '16 at 13:48
  • Possible duplicate of [Is there any way to ignore some properties (on a POCO) when validating a form in ASP.NET MVC3?](http://stackoverflow.com/questions/5209252/is-there-any-way-to-ignore-some-properties-on-a-poco-when-validating-a-form-in) – Eugene Podskal Jul 10 '16 at 14:02
  • Always use view models when editing - [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Jul 10 '16 at 23:15

1 Answers1

0

From a design perspective, you should create a model dedicated specifically for the view and then on the controller, populate the existing model with the data that was send to the client with the additional values you need to save to the database (i.e CreateOn, LastModified, etc.).

Hope it helps!

Itay Podhajcer
  • 2,616
  • 2
  • 9
  • 14
  • It does; though I have to display CreateOn, LastModified in the view; only in the create I do not want to show it. I will create a new model just for create and edit. – Amit Jul 10 '16 at 14:19
  • You can always do a "work around" using HiddenFor extension method, but it's ugly. Creating a dedicated model, in my opinion, is the right way to go. – Itay Podhajcer Jul 10 '16 at 16:40