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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T17:55:36+00:00 2026-06-17T17:55:36+00:00

I’m completely new to MVC and I’m trying to figure out why a validation

  • 0

I’m completely new to MVC and I’m trying to figure out why a validation summary isn’t displaying. Here’s the code:

view:

<% using(var form = Html.BeginForm("Create", "User"))
{%>
    <table>
        <thead>
            <th>Create User</th>
            <th><%= Html.ValidationSummary(false) %></th>
        </thead>
        <tbody>
            <tr>
                <td><%= Html.LabelFor(model => model.Creating.Username) %>:</td>
                <td><%= Html.TextBoxFor(model => model.Creating.Username) %></td>
            </tr>
            <tr>
                <td><%= Html.LabelFor(model => model.Creating.Firstname) %>:</td>
                <td><%= Html.TextBoxFor(model => model.Creating.Firstname)%></td>
            </tr>
            <tr>
                <td><%= Html.LabelFor(model => model.Creating.Lastname) %></td>
                <td><%= Html.TextBoxFor(model => model.Creating.Lastname) %></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Create" />
                </td>
            </tr>
        </tbody>
    </table>

<%}%>

Relevant controller method:

[HttpPost]
public ActionResult Create(User creating)
{
    var response = _service.Save(creating);
    if (response.Success)
        return RedirectToAction("Index");
    response.Errors.CopyToModelState(this.ModelState);
    return RedirectToAction("Index");
}

Business logic method:

public Response Save(User user)
{
    //Place Validation logic here
    //Check username is between 3-30 characters and make sure the username is unique
    //return response if username fails business rules

    bool isDataInvalid = false;
    List<ValidationError> errorList = new List<ValidationError>();
    if ((user.Username.Length < 3) || user.Username.Length > 30)
    {
        ValidationError invalidUsernameLengthError = new ValidationError();
        invalidUsernameLengthError.Property = "Creating.Username";
        invalidUsernameLengthError.ErrorMessage = "must be between 3 and 30 characters long";
        errorList.Add(invalidUsernameLengthError);
        isDataInvalid = true;
    }

    if (isDataInvalid)
    {
        return new Response()
        {
            Success = false,
            Errors = errorList
        };   
    }

    _repository.Save(user);

    return new Response()
    {
        Success = true
    };
}

Helper method:

public static void CopyToModelState(this List<ValidationError> errors,  ModelStateDictionary modelState)
{
    foreach (var error in errors)
    {
        modelState.AddModelError(error.Property, error.ErrorMessage);
    }
}

The logic does what it’s supposed to, but nothing displays. I’ve checked the HTML that gets output, and the validation is just not being written. I’ve tried assigning properties of the model to the modelState and displaying validation directly on the relevant fields, but this doesn’t work either. Any ideas?


Ah! doing a RedirectToAction causes a fresh request, so the error data is lost. Also I’m using a different controller so I need to explicitly call the original view (Index.aspx). Also the model that my index.aspx expects isn’t actually a user object, it’s a different list object, so I needed to do:

        var users = _service.FindAll();
        return View("Index", new UserListModel() { Users = users });

instead of the RedirectToAction. This is apparently the standard pattern for validating errors – for success (no errors) you use a RedirectToAction, but for errors, you need to return the correct view.


OK, thanks mattytommo – that’s really useful. I’m still getting problems though. I now have this for the controller – similar to what you suggested, but still no display of the error messages. I tried the data annotation but couldn’t get it to work (I’m using MVC2), and have been trying everything I can think of to get the existing code fixed.

    [HttpPost]
    public ActionResult Create(User creating)
    {
        var response = _service.Save(creating);
        if (response.Success)
            return RedirectToAction("Index");

        foreach (var error in response.Errors)
        {
            ModelState.AddModelError(error.Property, error.ErrorMessage);
        }

        return RedirectToAction("Index");
    }

Any more ideas? I appreciate the advice!

  • 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-17T17:55:38+00:00Added an answer on June 17, 2026 at 5:55 pm

    I think you’re passing the ModelState variable by value, so changes you make in that function are not actually being kept. Try reproducing what your function does, but to the actual ModelState object, like so:

    [HttpPost]
    public ActionResult Create(User creating)
    {
        var response = _service.Save(creating);
        if (response.Success)
            return RedirectToAction("Index");
    
        foreach (var error in response.Errors)
        {
            ModelState.AddModelError(error.Property, error.ErrorMessage);
        }
    
        return View(creating);
    }
    

    You should also check out MVC Data Annotations, validation like yours can simply be replaced by putting these two attributes on the Username property:

    [MinLength(3), MaxLength(30)]
    public string UserName { get; set; }
    

    Or just one attribute using StringLength (thanks @SimonWhitehead):

    [StringLength(30, MinimumLength = 3)]
    

    Data annotations: Here

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

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I am using JSon response to parse title,date content and thumbnail images and place
I have a small JavaScript validation script that validates inputs based on Regex. I

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.