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.
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:
On to details then...
Custom exception class
This class provides two things
This class is later used in my custom error filter.
Error filter attribute
This attribute helps returning errors to the client in terms of HTTP error codes when there are any model state errors.
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).
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 setsStatusDescription
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.
Try this.