Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8061487
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T10:21:19+00:00 2026-06-05T10:21:19+00:00

In Short : How do I successfully edit a DB entry without needing to

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T10:21:21+00:00Added an answer on June 5, 2026 at 10:21 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

here is the screen shot of my database! i have successfully done the insert
Short version: I have a similar setup to StackOverflow. Users get Achievements. I have
Short Question I have a loop that runs 180,000 times. At the end of
Edit - in short, what I'm looking for is a reliable way to add
G'day, Edit: We've been using Scrum very successfully for several years on several projects
Short Intro Currently I have a UITableView which is filled with custom cells that
Short version of what I want to accomplish : I have a foot pedal
I recently started rewriting an application and I'm trying to port it to model/view
EDIT I have effectively rewritten this question in order to greatly improve its quality
Hi I have a two MVC Telerik Grids Showing up in one View. Each

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.