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 7901923
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T09:21:30+00:00 2026-06-03T09:21:30+00:00

My ViewModel is not being properly rehydrated after failed vailidation on HttpPost resulting in

  • 0

My ViewModel is not being properly rehydrated after failed vailidation on HttpPost resulting in a ‘Object reference not set to an instance of an object‘ error on ‘CartItems’ when the view is being re-displayed.

How do I rehydrate my ViewModel so it can be re-displayed with error messages?

I have tried using @Html.HiddenFor(...) to persist the non-displayed values (as per this answer) but this did not work.

ViewModel

    public class CheckoutViewModel
    {
        public List<Cart> CartItems { get; set; }
        [DisplayFormat(DataFormatString = "${0:F2}")]
        public double CartTotal { get; set; }
        public virtual Order Order { get; set; }
    }

Controller GET: ActionResult

    //GET: /Checkout/AddressAndPayment
    public ActionResult AddressAndPayment()
    {
        var order = new Order();
        order.Username = User.Identity.Name;
        MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
        storeDB.SaveChanges();

        var cart = ShoppingCart.GetCart(this.HttpContext);

        // Set up the ViewModel
        var viewModel = new CheckoutViewModel
        {
            CartItems = cart.GetCartItems(),
            CartTotal = cart.GetTotal(),
            Order = order
        };

        // Return the view
        return View(viewModel);
    }

Controller POST: ActionResult

    [HttpPost]
    public ActionResult AddressAndPayment(CheckoutViewModel checkoutViewModel)
    {
        TryValidateModel(checkoutViewModel);
        try
        {
            checkoutViewModel.Order.Username = User.Identity.Name;
            checkoutViewModel.Order.OrderDate = DateTime.Now;
            storeDB.Orders.Add(checkoutViewModel.Order);

            // Error occurs on the following line if a custom data annotation validation attribute fails
            storeDB.SaveChanges();

            var cart = ShoppingCart.GetCart(this.HttpContext);
            cart.CreateOrder(checkoutViewModel.Order);
            storeDB.SaveChanges();

            return RedirectToAction("Complete", new { id = checkoutViewModel.Order.OrderID });
        }
        catch
        {
            //Invalid - redisplay with errors
            return View(checkoutViewModel);
        }
    }

Edit #1
@SoWeLie talked me through it and I have fixed the problem.
To rehydrate the cartItems in my ViewModel before passing it back to the View I added the following code to the catch block of my HttpPost ActionResult. This code basically calls methods which hit the DB to get the necessary info for the cart:

catch
        {
            //Invalid - redisplay with errors
            //The model is not valid, we need to redisplay the same view so that the user can fix the errors => fetch the cartItems
             var cart = ShoppingCart.GetCart(this.HttpContext);
             checkoutViewModel.CartItems = cart.GetCartItems();
             checkoutViewModel.CartTotal = cart.GetTotal();

            return View(checkoutViewModel);
        }
  • 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-03T09:21:32+00:00Added an answer on June 3, 2026 at 9:21 am

    You wouldn’t want to persist entire objects such as a list of CartItem in hidden fields. Attempting to carry all that data around as post values is inefficient and difficult to maintain. Your cart object needs to be persisted somewhere within the application such as the database. You could also store the cart in the user’s session.

    The best method for accomplishing this would be to save the user’s cart in the database. There are a number of ways you can do this. Without knowing your database model, the easiest solution would be to add the cart and its items to the database then take the cart id and store it either in the session or a cookie (depending on how long you want the cart to be persisted).

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

Sidebar

Related Questions

Possible Duplicate: WPF: XAML property declarations not being set via Setters? I am stuck
Short Version If I update the Model object that my ViewModel wraps, what's a
I have a native C DLL being invoked by a C++/CLI object which is
I created a ViewModel object that has a decimal field containing a price. When
Is Model-View-ViewModel the best pattern to use in WPF? Are there any downsides?
I have a ViewModel class that contains a list of points, and I am
I have a ViewModel which exposes the string property PageToolBarVisible which can be true
I have a ViewModel (AbstractContextMenu) that represents my context menu (IContextMenu), and I bind
I have a viewmodel that contains a product and SelectList of categories. public class
I have a viewmodel that contains a number of properties, a SelectList, and an

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.