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

  • Home
  • SEARCH
  • 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 617069
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T18:23:41+00:00 2026-05-13T18:23:41+00:00

I have a POST controller action that returns a partial view. Everything seems really

  • 0

I have a POST controller action that returns a partial view. Everything seems really easy. but. I load it using $.ajax(), setting type as html. But when my model validation fails I thought I should just throw an error with model state errors. But my reply always returns 500 Server error.

How can I report back model state errors without returning Json with whatever result. I would still like to return partial view that I can directly append to some HTML element.

Edit

I would also like to avoid returning error partial view. This would look like a success on the client. Having the client parse the result to see whether it’s an actual success is prone to errors. Designers may change the partial view output and this alone would break the functionality. So I want to throw an exception, but with the correct error message returned to the ajax client.

  • 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-13T18:23:41+00:00Added an answer on May 13, 2026 at 6:23 pm

    Solution

    I had to write two separate parts that automagically work exactly as intended.

    So it should return a partial view when controller action process succeeds and it should throw an error with some failure details when things are not ok so things on the client side would distinguish success as well as failure instead of always handling success.

    There are two major parts that are used to achieve this:

    • A custom exception class that is thrown when something goes wrong so we can distinguish between general exceptions that can happen any time for whatever reason and errors related to our processing (most notably invalid model state)
    • Exception action filter that catches our custom exception and prepares result based on that exception; As you’ll see from the code, our custom exception will hold information about model state errors so this filter will be able to return custom HTTP status code as well some textual information

    On to details then…

    External link: All this information (detailed explanation as well as all the code) is also available on my blog. Latest code updates will always be published there.

    Custom exception class

    This class provides two things

    1. make it simple to distinguish model state errors from regular exceptions
    2. provide some basic functionality I can use later

    This class is later used in my custom error filter.

    public class ModelStateException : Exception
    {
        public Dictionary<string, string> Errors { get; private set; }
    
        public ModelStateDictionary ModelState { get; private set; }
    
        public override string Message
        {
            get
            {
                if (this.Errors.Count > 0)
                {
                    return this.Errors.First().Value;
                }
                return null;
            }
        }
    
        private ModelStateException()
        {
            this.Errors = new Dictionary<string, string>();
        }
    
        public ModelStateException(ModelStateDictionary modelState) : this()
        {
            this.ModelState = modelState;
            if (!modelState.IsValid)
            {
                foreach (KeyValuePair<string, ModelState> state in modelState)
                {
                    if (state.Value.Errors.Count > 0)
                    {
                        this.Errors.Add(state.Key, state.Value.Errors[0].ErrorMessage);
                    }
                }
            }
        }
    }
    

    Error filter attribute

    This attribute helps returning errors to the client in terms of HTTP error codes when there are any model state errors.

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class HandleModelStateExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
    
            if (filterContext.Exception != null && typeof(ModelStateException).IsInstanceOfType(filterContext.Exception) && !filterContext.ExceptionHandled)
            {
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.ContentEncoding = Encoding.UTF8;
                filterContext.HttpContext.Response.HeaderEncoding = Encoding.UTF8;
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                filterContext.HttpContext.Response.StatusCode = 400;
                filterContext.HttpContext.Response.StatusDescription = (filterContext.Exception as ModelStateException).Message;
            }
        }
    }
    

    After that, I simply decorated my controller action with my attribute and voila. I did get errors on the client with code 400 and correct information that I set in my filter. This information is then displayed to the user (when it’s related to model state errors it displays information which form fields user should amend to make the form valid).

    [HandleModelStateException]
    public ActionResult AddComment(MyModel data)
    {
        // check if state is valid
        if (!this.ModelState.IsValid)
        {
            throw new ModelStateException(this.ModelState);
        }
        // get data from store
        return PartialView("Comment", /* store data */ );
    }
    

    This makes my code reusable with any model state errors and those will get sent to the client as they should.

    One single issue (is now resolved)

    But there’s still one issue related to this code. When my error action filter sets StatusDescription and that string contains some special characters like Č, I get rubbish on the client. Unless I use IE (I’m using version 8). FF and CH display rubbish. That’s why I set encodings but it doesn’t work. If anyone has a workaround for this particularity I’d be more than glad to listen in.
    If I return error message in content itself, everything’s fine. Encoding is correct and I can display whatever I want.

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

Sidebar

Ask A Question

Stats

  • Questions 383k
  • Answers 383k
  • 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 You might consider using this lib: http://iphoneonrails.com/ May 14, 2026 at 10:42 pm
  • Editorial Team
    Editorial Team added an answer Yes, quite. There is an open issue in integrate this… May 14, 2026 at 10:42 pm
  • Editorial Team
    Editorial Team added an answer You need to use the FormattedValue property of the DataGridViewCellValidatingEventArgs… May 14, 2026 at 10:42 pm

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.