I have a "submit feedback" form which uses "Ajax.BeginForm" to render a partial containing the form elements. The OnSuccess event is triggering even if the ModelState is not valid. Is this normal? I was expecting to be able to do a few postbacks resulting in an invalid model, then when the model is valid and there are no errors then the OnSuccess event would trigger?
相关问题
- Carriage Return (ASCII chr 13) is missing from tex
- Using :remote => true with hover event
- Is there a way to play audio on a mobile browser w
- net::ERR_EMPTY_RESPONSE when post with ajax
- Easiest way to get json and parse it using JQuery
相关文章
- spring boot用ajax发送请求后,请求路径多了controller的路径
- 针对复杂结构的前端页面,如何更好地与后台交互实现动态网页?
- ajax上传图片,偶尔会出现后台保存的图片有错误或者已损坏,请问可能是什么原因造成的?
- 前端 我想知道怎样通过发ajax请求向服务器拿到数据然后分页显示 最好是点击一页就发一次请求
- 接口返回的数据格式如下,请问可以取到level值为2的name数组呢
- 如何通过页面输入账号密码提交给后端
- “Dynamic operations can only be performed in homog
- How to get jQuery.ajax response status?
You can do the following:
I handle this issue with a fairly simple javascript technique:
First setup your
OnSuccess
like this:Then your javascript function like this:
This way, there is no need to mess with your controller, or more importantly, your controller can return the
Partial View
with the model errors without doing anything weird, ie:And in your
AjaxOptions
:Now just make sure you have a
div
or something withid="FormContents"
wherever you want your form displayed.I return a bad request instead of the View to ensure that the ajax call returns onfail and not onsuccess.
In the xhr.statustext you can find the string written in the bad request and manage correctly the onfail event.
Server side:
Client side:
Slight variation on Luis' answer:
Yes, of course. If the server sends HTTP 200 the OnSuccess method is called. The notion of modelstate validity is server side only. As long as your controller action returns some view/partial/json/... the OnSuccess will trigger. If an exception is thrown inside your controller action then the OnError will be triggered instead of OnSuccess.
So in order to handle this case you could have your controller action do something along the lines of:
and then:
Now in the case of invalid model you might want to show the error messages to the user by refreshing the form. What you could do in this case is place your form inside a partial and in the event of an invalid modelstate you would return a partialview from your controller action and in the case of success a json object. So in your success handler you could test: