Successful Model Editing without a bunch of hidden fields
Asked Answered
B

5

11

In Short: How do I successfully edit a DB entry without needing to include every single field for the Model inside of the Edit View?

UPDATE
So I have an item in the DB (an Article). I want to edit an article. The article I edit has many properties (Id, CreatedBy, DateCreated, Title, Body). Some of these properties never need to change (like Id, CreatedBy, DateCreated). So in my Edit View, I only want input fields for fields that can be changed (like Title, Body). When I implement an Edit View like this, Model Binding fails. Any fields that I didn't supply an input for gets set to some 'default' value (like DateCreated gets set to 01/01/0001 12:00:00am). If I do supply inputs for every field, everything works fine and the article is edited as expected. I don't know if it's correct in saying that "Model Binding fails" necessarily, so much as that "the system fills in fields with incorrect data if no Input field was supplied for them in the Edit View."

How can I create an Edit View in such a way that I only need to supply input fields for fields that can/need editing, so that when the Edit method in the Controller is called, fields such as DateCreated are populated correctly, and not set to some default, incorrect value? Here is my Edit method as it currently stands:

    [HttpPost]
    public ActionResult Edit(Article article)
    {
        // Get a list of categories for dropdownlist
        ViewBag.Categories = GetDropDownList();


        if (article.CreatedBy == (string)CurrentSession.SamAccountName || (bool)CurrentSession.IsAdmin)
        {                
            if (ModelState.IsValid)
            {
                article.LastUpdatedBy = MyHelpers.SessionBag.Current.SamAccountName;
                article.LastUpdated = DateTime.Now;
                article.Body = Sanitizer.GetSafeHtmlFragment(article.Body);

                _db.Entry(article).State = EntityState.Modified;
                _db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }
            return View(article);
        }

        // User not allowed to edit
        return RedirectToAction("Index", "Home");   
    }

And the Edit View if it helps:

. . .
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>Article</legend>

    <p>
        <input type="submit" value="Save" /> | @Html.ActionLink("Back to List", "Index")
    </p>

    @Html.Action("Details", "Article", new { id = Model.Id })

    @Html.HiddenFor(model => model.CreatedBy)
    @Html.HiddenFor(model => model.DateCreated)

    <div class="editor-field">
        <span>
            @Html.LabelFor(model => model.Type)
            @Html.DropDownListFor(model => model.Type, (SelectList)ViewBag.Categories)
            @Html.ValidationMessageFor(model => model.Type)
        </span>
        <span>
            @Html.LabelFor(model => model.Active)
            @Html.CheckBoxFor(model => model.Active)
            @Html.ValidationMessageFor(model => model.Active)
        </span>
        <span>
            @Html.LabelFor(model => model.Stickied)
            @Html.CheckBoxFor(model => model.Stickied)
            @Html.ValidationMessageFor(model => model.Stickied)
        </span>            
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Title)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Title)
        @Html.ValidationMessageFor(model => model.Title)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Body)
    </div>
    <div class="editor-field">
        @* We set the id of the TextArea to 'CKeditor' for the CKeditor script to change the TextArea into a WYSIWYG editor. *@
        @Html.TextAreaFor(model => model.Body, new { id = "CKeditor", @class = "text-editor" })
        @Html.ValidationMessageFor(model => model.Body)
    </div>
</fieldset>
. . .

If I were to leave out these two inputs:

@Html.HiddenFor(model => model.CreatedBy)
@Html.HiddenFor(model => model.DateCreated)

when the Edit method is called, they're set to default values. CreatedBy is set to Null, Created is set to 01/01/0001 12:00:00am

Why are they not set to the values as they are currently set to in the DB?

Brow answered 7/6, 2012 at 16:19 Comment(2)
You can also use TryUpdateModel(existingArticle) instead of setting every field. Some solution may not seem too elegant, but there are solutions like AutoMapper, that you can use later, that will solve this problem, but right now you don't have to know it yet.Shirleeshirleen
But if it's the "right" way, of course I want to know it now ;) I've been doing a bit of digging and it seems like, yes, using these things called "ViewModels" is the way to go: a way to "show a slice of information from a single entity." Apparently it's a little bit more work, but as models/views get more complex they hold strong, whereas these other "brute force" methods tend to break down.Brow
B
11

After yet some more research I came upon some tools that assist in the ViewModel process - one being AutoMapper & the other InjectValues. I went with InjectValues primarily because it can not only "flatten" objects (map object a -> b) but it can also "unflatten" them (map object b -> a) - something that AutoMapper unfortunately lacks out-of-the-box - something I need to do in order to update values inside of a DB.

Now, instead of sending my Article model with all of its properties to my views, I created an ArticleViewModel containing only the following properties:

public class ArticleViewModel
{
    public int Id { get; set; }

    [MaxLength(15)]
    public string Type { get; set; }

    public bool Active { get; set; }
    public bool Stickied { get; set; }

    [Required]
    [MaxLength(200)]
    public string Title { get; set; }

    [Required]
    [AllowHtml]
    public string Body { get; set; }
}

When I Create an Article, instead of sending an Article object (with every property) I send the View a 'simpler' model - my ArticleViewModel:

//
// GET: /Article/Create

public ActionResult Create()
{
    return View(new ArticleViewModel());
}

For the POST method we take the ViewModel we sent to the View and use its data to Create a new Article in the DB. We do this by "unflattening" the ViewModel onto an Article object:

//
// POST: /Article/Create
public ActionResult Create(ArticleViewModel articleViewModel)
{
    Article article = new Article();              // Create new Article object
    article.InjectFrom(articleViewModel);         // unflatten data from ViewModel into article 

    // Fill in the missing pieces
    article.CreatedBy = CurrentSession.SamAccountName;   // Get current logged-in user
    article.DateCreated = DateTime.Now;

    if (ModelState.IsValid)
    {            
        _db.Articles.Add(article);
        _db.SaveChanges();
        return RedirectToAction("Index", "Home");
    }

    ViewBag.Categories = GetDropDownList();
    return View(articleViewModel);            
}

The "missing pieces" filled in are Article properties I didn't want to set in the View, nor do they need to be updated in the Edit view (or at all, for that matter).

The Edit method is pretty much the same, except instead of sending a fresh ViewModel to the View we send a ViewModel pre-populated with data from our DB. We do this by retrieving the Article from the DB and flattening the data onto the ViewModel. First, the GET method:

    //
    // GET: /Article/Edit/5
    public ActionResult Edit(int id)
    {
        var article = _db.Articles.Single(r => r.Id == id);     // Retrieve the Article to edit
        ArticleViewModel viewModel = new ArticleViewModel();    // Create new ArticleViewModel to send to the view
        viewModel.InjectFrom(article);                          // Inject ArticleViewModel with data from DB for the Article to be edited.

        return View(viewModel);
    }

For the POST method we want to take the data sent from the View and update the Article stored in the DB with it. To do this we simply reverse the flattening process by 'unflattening' the ViewModel onto the Article object - just like we did for the POST version of our Create method:

    //
    // POST: /Article/Edit/5
    [HttpPost]
    public ActionResult Edit(ArticleViewModel viewModel)
    {
        var article = _db.Articles.Single(r => r.Id == viewModel.Id);   // Grab the Article from the DB to update

        article.InjectFrom(viewModel);      // Inject updated values from the viewModel into the Article stored in the DB

        // Fill in missing pieces
        article.LastUpdatedBy = MyHelpers.SessionBag.Current.SamAccountName;
        article.LastUpdated = DateTime.Now;

        if (ModelState.IsValid)
        {
            _db.Entry(article).State = EntityState.Modified;
            _db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }

        return View(viewModel);    // Something went wrong
    }

We also need to change the strongly-typed Create & Edit views to expect an ArticleViewModel instead of an Article:

@model ProjectName.ViewModels.ArticleViewModel

And that's it!

So in summary, you can implement ViewModels to pass just pieces of your Models to your Views. You can then update just those pieces, pass the ViewModel back to the Controller, and use the updated information in the ViewModel to update the actual Model.

Brow answered 11/6, 2012 at 17:31 Comment(2)
Thanks for keeping this question up-to-date. One final thing to note, make sure your Id is a hidden field in your view: @Html.HiddenFor(model => model.Id)Disarm
+1 for finding Value Injector from Codeplex. That's a lovely little library.Frazer
S
2

View model example:

public class ArticleViewModel {
    [Required]
    public string Title { get; set; }

    public string Content { get; set; }
}

Binding example

public ActionResult Edit(int id, ArticleViewModel article) {
    var existingArticle = db.Articles.Where(a => a.Id == id).First();
    existingArticle.Title = article.Title;
    existingArticle.Content = article.Content;
    db.SaveChanges();
}

That is simple example, but you should look at ModelState to check if model doesn't have errors, check authorization and move this code out of controller to service classes, but that is another lesson.

This is corrected Edit method:

[HttpPost]
public ActionResult Edit(Article article)
{
    // Get a list of categories for dropdownlist
    ViewBag.Categories = GetDropDownList();


    if (article.CreatedBy == (string)CurrentSession.SamAccountName || (bool)CurrentSession.IsAdmin)
    {                
        if (ModelState.IsValid)
        {
            var existingArticle = _db.Articles.First(a => a.Id = article.Id);
            existingArticle.LastUpdatedBy = MyHelpers.SessionBag.Current.SamAccountName;
            existingArticle.LastUpdated = DateTime.Now;
            existingArticle.Body = Sanitizer.GetSafeHtmlFragment(article.Body);
            existingArticle.Stickied = article.Stickied;

            _db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }
        return View(article);
    }

    // User not allowed to edit
    return RedirectToAction("Index", "Home");   
}
Shirleeshirleen answered 7/6, 2012 at 17:39 Comment(10)
So with a ViewModel you still need to provide (in the view) an input for every field in order for the Model Binder (at least the default one) to successfully bind to the model, is that correct? In your example I would need to provide an input for both the "Title" and "Content" fields. In that case I would find it easier to simply do what I've been doing - provide hidden fields in the view for non-changing fields (Id, DateCreated, etc.). That would save me from needing to create a view model for every one of my models.Brow
@cbergman: That is the way MVC is meant to be played. Hidden fields can be easily manipulated and changed. Making field hidden doesn't protect values from being changed. Someone can still change hidden field and modify something, that you didn't want to modify. Please read this recent question: #10928787Shirleeshirleen
I was thinking that the Model Binder would be able to find a certain Article by its passed ID, populate each of the fields itself (that already contain values), and only modify each of the fields that have been edited inside the View. But apparently (as has been the case with me, anyway) if it doesn't find an input for that field passed by the View, it will populate that field with a "default" value (e.g. A DateTime field with '01/01/0001 12:00:00am'). If that DateTime field were, say, the DateCreated field, obviously this would be wrong.Brow
Good point about malicious users editing hidden fields, though. So ViewModels are the way to go, eh? Could you possibly point me in the direction of some good articles (maybe a book) that discusses and explains their uses? I've gone through quite a few different tutorials and have been reading a couple of books (one being "Professional ASP.NET MVC 3") and have never ran into them before :/Brow
@cbergman: Model Binder won't retrieve your article from database and it is not designed to do it. I am sorry, I didn't understand your problem. You have to retrieve article from database yourself, update its properties with values from view model and save it to database.Shirleeshirleen
That's okay. I don't think I quite understand what I'm asking, myself. I've updated my post with more information. I hope that helps in what I'm trying to get across.Brow
@cbergman: I updated answer. You should retrieve entity from database first, then update its fields and save changes.Shirleeshirleen
That works for the three fields that I edit inside of the controller (LastUpdatedBy, LastUpdated, and Body). But other changes only made inside of the Edit View (like the Sticky & Active checkboxes) get lost; their changes are not saved.Brow
So please add existingArticle.Stickied = article.Stickied; to set fields from form.Shirleeshirleen
Doing that for every property just doesn't seem very...elegant. I'm confused as to why I can write inside of my Edit View: <p>DateCreated: @Model.DateCreated</p> <p>LastUpdated: @Model.LastUpdated</p> And it knows what I'm talking about (in the GET request). It correctly pulls up "DateCreated: 06/02/2012 8:30:47am" & "LastUpdated: 06/05/2012 9:37:51am" (as an example). But as soon as I click the "Submit" button, that information is lost. Both fields are set to 01/01/0001 12:00:00am.Brow
S
2

another good way without viewmodel

// POST: /Article/Edit/5
[HttpPost]
public ActionResult Edit(Article article0)
{
    var article = _db.Articles.Single(r => r.Id == viewModel.Id);   // Grab the Article from the DB to update

   article.Stickied = article0.Stickied;

    // Fill in missing pieces
    article.LastUpdatedBy = MyHelpers.SessionBag.Current.SamAccountName;
    article.LastUpdated = DateTime.Now;

    if (ModelState.IsValid)
    {
       _db.Entry(article0).State = EntityState.Unchanged;
        _db.Entry(article).State = EntityState.Modified;
        _db.SaveChanges();
        return RedirectToAction("Index", "Home");
    }

    return View(article0);    // Something went wrong
}
Subfusc answered 2/8, 2015 at 6:59 Comment(1)
Not great if you want to keep your application and data layers separate.Nabonidus
B
0

Use ViewModels.

Through my continued research of finding a solution to this issue I believe that using these things called "ViewModels" is the way to go. As explained in a post by Jimmy Bogard, ViewModels are a way to "show a slice of information from a single entity."

asp.net-mvc-view-model-patterns got me headed on the right track; I'm still checking out some of the external resources the author posted in order to further grasp the ViewModel concept (The blog post by Jimmy being one of them).

Brow answered 8/6, 2012 at 14:47 Comment(0)
S
0

In addition to the answer, AutoMapper can also be used to unflatten it. Using AutoMapper to unflatten a DTO

Smalt answered 28/8, 2015 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.