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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T07:45:52+00:00 2026-05-14T07:45:52+00:00

Serious n00b warning here; please take mercy! So I finished the Nerd Dinner MVC

  • 0

Serious n00b warning here; please take mercy!

So I finished the Nerd Dinner MVC Tutorial and I’m now in the process of converting a VB.NET application to ASP.NET MVC using the Nerd Dinner program as a sort of rough template.

I am using the “IsValid / GetRuleViolations()” pattern to identify invalid user input or values that violate business rules. I am using LINQ to SQL and am taking advantage of the “OnValidate()” hook that allows me to run the validation and throw an application exception upon trying to save changes to the database via the CustomerRepository class.

Anyway, everything works well, except that by the time the form values reach my validation method invalid types have already been converted to a default or existing value. (I have a “StreetNumber” property that is an integer, though I imagine this would be a problem for DateTime or any other non-strings as well.)

Now, I am guessing that the UpdateModel() method throws an exception and then alters the value because the Html.ValidationMessage is displayed next to the StreetNumber field but my validation method never sees the original input. There are two problems with this:

  1. While the Html.ValidationMessage does signal that something is wrong, there is no corresponding entry in the Html.ValidationSummary. If I could even get the exception message to show up there indicating an invalid cast or something that would be better than nothing.

  2. My validation method which resides in my Customer partial class never sees the original user input so I do not know if the problem is a missing entry or an invalid type. I can’t figure out how I can keep my validation logic nice and neat in one place and still get access to the form values.

I could of course write some logic in the View that processes the user input, however that seems like the exact opposite of what I should be doing with MVC.

Do I need a new validation pattern or is there some way to pass the original form values to my model class for processing?


CustomerController Code

    // POST: /Customers/Edit/[id]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection formValues)
    {
        Customer customer = customerRepository.GetCustomer(id);

        try
        {
            UpdateModel(customer);

            customerRepository.Save();

            return RedirectToAction("Details", new { id = customer.AccountID });
        }
        catch
        {
            foreach (var issue in customer.GetRuleViolations())
                ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
        }
        return View(customer);
    }

  • 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-14T07:45:53+00:00Added an answer on May 14, 2026 at 7:45 am

    This would be a good starting point: Scott Gu – ASP.NET MVC 2: Model Validation

    But I would suggest that it’s bad practice to databind stuff to your domain objects.

    My personal approach would be to use POCO presentation models sprinkled with DataAnnotations validation attributes to do validation (this makes it easy to hook up client side validation later on). You can also create you own ValidationAttributes to hook into the databinding validation.

    If it’s valid after databinding to your POCO object, pass it a service that does your more complex business validation. After that validation passes, pass it to another service (or the same service) that transfers the values to your domain object and then saves it.

    I’m not familiar with the Linq to SQL GetRuleViolations pattern, so feel free to replace one of my steps with that pattern where it fits.

    I’ll try my best to explain it here.

    POCO presentation model:

    public class EditCustomerForm
    {
        [DisplayName("First name")]
        [Required(ErrorMessage = "First name is required")]
        [StringLength(60, ErrorMessage = "First name cannot exceed 60 characters.")]
        public string FirstName { get; set; }
    
        [DisplayName("Last name")]
        [Required(ErrorMessage = "Last name is required")]
        [StringLength(60, ErrorMessage = "Last name cannot exceed 60 characters.")]
        public string LastName { get; set; }
    
        [Required(ErrorMessage = "Email is required")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                           @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                           @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                           ErrorMessage = "Email appears to be invalid.")]
        public string Email { get; set; }
    }
    

    Controller logic

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, EditCustomerForm editCustomerForm)
    {
        var editCustomerForm = CustomerService.GetEditCustomerForm(id);
    
        return View(editCustomerForm);
    }
    
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, EditCustomerForm editCustomerForm)
    {
        try
        {
            if (Page.IsValid)
            {
                //Complex business validation that validation attributes can't handle
                //If there is an error, I get this method to throw an exception that has
                //the errors in it in the form of a IDictionary<string, string>
                CustomerService.ValidateEditCustomerForm(editCustomerForm, id);
    
                //If the above method hasn't thrown an exception, we can save it
                //In this method you should map the editCustomerForm back to your Cusomter domain model
                CustomerService.SaveCustomer(editCustomerForm, id)
    
                //Now we can redirect
                return RedirectToAction("Details", new { id = customer.AccountID });
        }
        //ServiceLayerException is a custom exception thrown by
        //CustomerService.ValidateEditCusotmerForm or possibly .SaveCustomer
        catch (ServiceLayerException ex)
        {
            foreach (var kvp in ex.Errors)
                ModelState.AddModelError(kvp.Key, kvp.Value);
        }
        catch (Exception ex) //General catch
        {
            ModelState.AddModelError("*", "There was an error trying to save the customer, please try again.");
        }
    
        return View(editCustomerForm);
    }
    

    Clear as mud? If you need more clarification, just let me know 🙂

    Again, this is just my approach. You could possibly just follow the article by Scott Gu I linked to first and then go from there.

    HTHs,
    Charles

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

Sidebar

Related Questions

I have a serious problem. One of our servers crashed. Now I reinstalled the
After some serious googleing I found out that the RandomAccessFile-class is not thread-safe. Now
serious database n0ob here, My question is as follow: I want to update a
I've got a serious issue here. I'm developing a forum, and trying to get
This is a very serious question: I've seen lots of threads here about gravatars
I got a serious problem here: I have a scrolling background that is 1320
I've had a serious issue with my Visual Studio 2008 setup. I receive the
I never did any serious Java coding before, but I learned the syntax, libraries,
I have a serious probleam with my Eclipse Plugin.. My plugin depends on another
I am having some serious issues trying to tweak my layout in a table.

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.