I am working on an ASP.NET MVC 2 application and am struggling to get the desired behavior from a dialog window in one of my pages. Think of it as something like the "Add New Item" window in Visual Studio.
When the user clicks a button on the main page, I use the jQuery dialog plug in to display a partial view containing a form. The partial view is strongly-type with DataAnotations used in the Model class to define validation rules. When the user submits the form with valid data, I navigate to another page.
Here are my problems:
开发者_JAVA百科- Submitting the "out-of-the-box" form (no extra code) messes everything up because returning the view back to the client sends it as the main page and no longer a partial view. This is great when I want to navigate away and use one of the RedirectXYZ overloads in my Action method. But when I want to return just the partial back to display validation errors, this is a major problem.
- Validation. I'd like to be able to provide the user with feedback when required fields are missing, etc. Using DataAnnotations means that I have to be able to post the page back to the server, check ModelState.IsValid and return the same view if false. As I said in the first bullet, this doesn't work with partial views. And, while I can enable AJAX validation support by including the MicrosoftXYZ.js files, they aren't tied into the submit button of the jQuery dialog so being invalid doesn't prevent submission. (Plus, I don't want to fix jQuery and AJAX code, if possible).
I tried enabling AJAX posting of the form (using the jQuery forms plugin) but without jQuery validation working with DataAnnotations, I am back to square one (plus I'd have to figure out how to redirect the page on a successful submission).
I can't be the first person to try and display a partial view containing a form in a jQuery dialog that requires validation. Any helps is greatly appreciated as I've lost a full day trying to find a solution.
Because you're using Javascript popups and sending data to server I suggest you use Ajax. So it will work as expected. If a user clicks Save it would be normal, that your popup form is submitted and saved and closed on the client (and most likely refresh the main page where popup came up).
Validation
Anyway. This blog post won't completely answer your question, but it will make it possible for you to handle model validation errors while using Ajax requests more appropriate. It explains the problem into great detail and provides the code you can use as is.
Redirection
Regarding HTTP redirects it's a bit more complicated since browsers do these things in different ways. Anyway. A different stackoverflow question will try to answer this.
精彩评论