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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T01:02:57+00:00 2026-05-12T01:02:57+00:00

Ok, I admit it – I wrote my own view state facility for ASP.NET

  • 0

Ok, I admit it – I wrote my own view state facility for ASP.NET MVC. I am interested in others’ critique, especially given all the view state bashing associated with WebForms. On the other hand, in Pro ASP.NET MVC Framework (p405-406) Steven Sanderson says “I feel that as a general web design pattern, [ViewState] is completely sound: web developers have always preserved data in hidden form fields; this just takes it to the next level by formalizing that technique and providing a neat abstraction layer.” Given my specific problem, it seemed like a reasonable approach to create such a lightweight abstraction layer while retaining MVC’s strengths of transparency and testability.

In question form:

  • Is using ViewData the best or at least a strong way to solve my problem?
  • Are there serious weaknesses (e.g., performance, security) in my specific approach?
  • How well does the approach fit with the MVC design esthetic?
  • Is there a better solution? If so, what is it and why?

I am writing a secure interface to administer users/roles/accounts – that sort of thing. Data retrieved from the database has a identity token and a timestamp used for optimistic concurrency control. For operations like editing, the identity and timestamp have to be associated with the client operation, which calls for some sort of client-side persistence. The timestamp is a key driver of this client-side persistence, since updating a record requires checking the retrieval timestamp against the current timestamp to see if another user has updated it since it was originally retrieved. The integrity of the timestamp must be perserved since a malicious user could overwrite database records by manipulating it.

The usual persistence options are ViewData, TempData, and session state. I didn’t seriously consider other options such as writing my own database facility. I chose ViewData since the data can be retained for more than a single round-trip (e.g., the state is retained even if a client jumps to another page and back) and because I wanted to avoid a lot of session data management. My thinking is that the approach will be fairly low overhead and secure, if only select data are stored in ViewData and if it is protected with a HMAC (hashing code message authentication) code.

In practice, I use a pair of functions Encode/Decode to serialize the data and calculate the HMAC code, and an Html helper Html.FormState() to store the serialized data on the form. (The Encode/Decode API is a little more involved than I show, enabling me to store multiple objects, etc.) I also pass the state back into the action method as an argument. This maintains a design with a functional flavor and thus promotes testability. Here’s a sample (the inline assignment to ViewData is just for illustration):

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Edit(Guid? id) {
        User user = _crmContext.Users.GetUser(id ?? Guid.Empty);
        if (user == null) {
            TempMessage = "User not found";
            return RedirectToAction("Index");
        }
        else {
            ViewData["formState"] = EncodeState("user", user);
            return View(user);
        }
    }

    [AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
    public ActionResult Edit(Guid? id, string formState) {
        User user = DecodeState("user", formState) as User;
        if (user == null || id != user.UserId) {
            TempMessage = "User not found";
            return RedirectToAction("Index");
        }
        else {
            try {
                UpdateModel(user, "user");
                _crmContext.Users.UpdateUser(user);
                TempMessage = "User changes saved.";
                return RedirectToAction("Details", new { id = user.UserId });
            }
            catch (RulesException e) {
                e.AddModelStateErrors(ModelState, "user");
                ViewData["formState"] = EncodeState("user", user);
                return View(user);
            }
        }
    }

    public static string FormState(this HtmlHelper html) {
        string anti = html.AntiForgeryToken();
        string data = html.Hidden("formState");
        return "\n" + anti + "\n" + data;
    }
  • 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-05-12T01:02:57+00:00Added an answer on May 12, 2026 at 1:02 am

    The question is reasonable.

    Web applications are going to need to store data between requests that’s associated with either the user, or the specific request. The typical mechanisms — hidden form values, server side state, and cookies — all have their advantages and disadvantages.

    When storing information specific to a given request, I tend to default towards hidden form values, because it offers the best scalability (no server-side information store). The downside is, of course, that the page can become bloated if you aren’t careful about exactly how much information you store. You also need to ensure that the posted-back data is valid, since it could be tampered with by bad guys (digital signatures and encryption both being reasonable solutions).

    So to me, your solution seems perfectly reasonable. I have done similar things in the past (with my Dynamic Data for MVC sample), even going so far as to build a custom model binder which allowed me to get access to the deserialized object directly in my action methods (which made unit testing them simpler, since they weren’t relying on having encrypted data in form fields).

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

Sidebar

Ask A Question

Stats

  • Questions 262k
  • Answers 262k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer That is the old and no longer recommended way of… May 13, 2026 at 11:48 am
  • Editorial Team
    Editorial Team added an answer I think I have the answer here, which is not… May 13, 2026 at 11:48 am
  • Editorial Team
    Editorial Team added an answer Yes, it is possible, you only need to create a… May 13, 2026 at 11:48 am

Related Questions

Ok, I admit it - I wrote my own view state facility for ASP.NET
The Back Story I have some decimal values which I am displaying as strings
What is a good Scheme IDE for Windows? OK, I'll admit it; I'm not
OK so I admit right off the top that this is a bit screwy
I admit that I use a somewhat long-winded bash prompt: --(username)-(Wed April 01|12:00:00)--(~ $

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.