asp.mvc how do I submit mulitple forms? - asp.net-mvc

I have an asp.mvc app the presents to the user different forms when they click on the next button - like a wizard. I do it this way so I can use JQuery to validate each form as the user progresses through them. i.e.
...
// use jquery validator to funk up the form validation
// user clicks the Next button ...
switch(currPageIndex) {
case 0:
if($('#form1'.valid()) {
$('#form1').hide();
$('#form2').show();
}
break;
}
...
However I can't use a single submit button to post the all the forms formcollection data back to my controller - if I do I only get back the one form that the submit button was in and not all of them.
Is there some magic icantation I can type in to get all the forms data sent back to the controller?
Presumably I can cruft up the data myself and send it back to my controller as a jason string, but I'm not sure if this is the best way.
Many thanks.

Wizard-like forms basically rely on a model which is kept on the server-side (in session or a database table) and kept updated.
For example, each post from the client you get back the model from session or database and then call UpdateModel() using the FormCollection which updates the model and the you can check if it is valid.

You can only submit one form at a time, however there are multiple ways around this in your scenario. When you change to the second form you could populate some hidden fields using javascript that would contain the information from the previous form. Then it would all be in the second form and you wouldn't have a problem getting the information.
You could also do it via ajax/json, but then you would probably want to do it with both of the forms data anyway.

In the end I just json'd up the form data and ajax'd it over to the controller, it works very well, nice and and clean to.
many thanks for the replies.

You can do that using $('#form1').submit() function, I don't think there is another way.

Related

ASP.Net MVC client side validation error - working for one button but not the other

I have a page with two submit butons; SaveAndContinue, and SaveAndExit. They are exactly the same except for CSS class and controller action.
The first one, SaveAndContinue will correctly validate client side and it will not post to the controller if ModelState.IsValid is false. Whereas the second one will completely skip the client side validation and post to the controller with ModelState.IsValid is false.
I'm using standard data annotations validation and nothing else is special. No fancy jQuery/AJAX functions.
Anyone any suggestions why one would work and the other not?
I'm using MVC 3, jQuery.validate, jQuery.validate.unobtrusive.
thanks in advance.
Are the submit buttons contained in different forms? If the submit button is not in the form that contains the inputs that have failed validation then the submit will still happen with no client-side errors.
The answer has been found (thanks to Osh) and it was glaring me in the face.
One of the CSS classes used by the second button was a 'cancel' class, which in itself didn't do much.
However, the validate function in jquery.validate-vsdoc.js specifically checks if the 'submitHandler' is a button with the class '.cancel', and if so sets the validator.cancelSubmit = true
this.find("input, button").filter(".cancel").click(function () {
validator.cancelSubmit = true;
});
Hope this helps someone else. :-)

What is the best practices to track action id in controller for saved form?

Wasnt sure how to word the question, but this is the scenario:
the view is a data entry form eg http://127.0.0.1/User/AddEdit/
so edit the user I have an ID: http://127.0.0.1/User/AddEdit/7838fd9c-425c-4c98-b798-771bba10d9c1
This ID gets the data to populate the form values in a ViewModel, which populates the form
I am using jquery/ajax to save the form, which returns a Json result, indicating ok/error etc
In the View, I get the ID and use this in a hidden field which is set via jquery when the page loads and when the form is saved via ajax.
This seems a bit clunky, how do others do this?
in my opinion best solution is to create a partial view with all the fields and use it on add and edit view which are separate actions in controller. after you create user you can redirect to action edit. if you must / like use ajax you can reload div with form (change from user/add to user/edit/1). i might be wrong but i never see a code or example with one action in controller for add and edit.

ASP.Net MVC2 -- After posting, how to clear form if user hits Back button?

In my web app, after clicking the Submit button on an ASP.NET MVC form, the user is displayed either an Error screen or a Success screen. In the case of the Error, the user is instructed to click the Back button on the browser and fix whatever they didn't do right and try submitting again.
This works fine because when the user clicks back, all the previously entered data is still in the screen in the various fields. But in the case of the Success screen, I would like the data to be cleared if the user clicks Back, so that they cannot just accidentally re-submit the data again.
How does one do this in ASP.NET MVC?
The way you can accomplish this is to use the Post-Get-Redirect pattern. It's not asp-mvc specific but as Wiki says it
a common design pattern for web developers to help avoid certain duplicate form submissions and allow user agents to behave more intuitively with bookmarks and the refresh button.
Clicking the back is not safe way to handle this. Some browsers don't maintain the form state after submission. This pattern directly address the accidentally re-submit data issue.
In terms of code, have a look at this blog post by Jag Reehal concerning how to unit test controllers.
[HttpPost]
public ActionResult Create(SomeViewModel model)
{
if (ModelState.IsValid)
{
// do some stuff that saves your data and then...
return RedirectToAction("Success");
}
else
{
// your model is not valid so return the form back to the user for
// additional modifications.
return View(model);
}
}
Note: while the above uses ModelState for data validation, you may have your own set of validations and error checking routines which can also be used in this pattern.

MVC validating multiple forms

In my MVC application for booking accommodation I have the following:
Action to display the selected room with input-forms for extra info GET:"Details"
This view has multiple forms on it, each posting to a different action.
Examples:
Action to update the number of guests POST:"UpdateGuests"
Action to select start date POST:"SelectStartDate"
Action to add breakfast POST:"AddBreakfast"
Action to delete room POST:"RemoveProductFromCart"
Action to proceed to next step POST:"Proceed"
Most of these actions will redirect back to the GET:"Details" view so the user can perform another action if required, in the case of the proceed, this will redirect to the next view OR if there is some reason they cannot proceed it will display the validation message as to why on the "Details" view.
I'm not sure of the best way to deal with validation, here's some options I've thought of.
use TempData[] to store validation messages and REDIRECT to "Details" view where we add any TempData errors so the ModelState.
in the POST:"xxxxxx" Action populate the ModelState and RENDER the "Details"
This is not a high volume site so TempData is an option.
Any ideas gratefully welcomed.
Edit:
Additional info:
I'm using DataAnnotations for validation rules in some places.
adding Ajax as progressive enhancement is planned, but it should work without.
I think that your second option is the best : each post actions will do the required validations, populate the ModelState with the error messages and every post will return the same view, rebuilt using your model.
Another option, a little bit harder but giving a much better user experience is to do some actions (like update number of people, select start date, add breakfast) using an ajax call. That way, you can return only the little bit of informations required by this action, refresh only that part of the screen and add some error messages if needed.
I hope it will help.
Have you taken a look at how nerd Dinner does validation? I've used this approach with forms that contain several Partial Views and it works great.
You can even modify to validate using jQuery on the fly if that's what you want to do.

ASP.NET MVC- submitting a client side created collection

I am using javascript to append user selections to a list. When user is done , which is the best way to go:
1: create index for the list and submit as model in a form to the controller?
2: create hidden element and use javascript to append values and submit as actionlink? (not sure how to tell actionlink the value here)
3: wrap form block around the hidden element only and submit string as model?
other?
I think the easiest way is to put some form of your list to the hidden field (type=hidden) and it will be automatically submitted with form and accessible on server under the name you gave it. So main reasoning here is the way you going to process these data on the server side.
First of all, Scott Hanselman has a good post about model binding to arrays, collections, etc.
In my opinion you shouldn't use second way because this will be a vulnerability ( description of CSRF).
In order to use collections binding you'll need to wrap a form around a list and submit it (note, this form will submit only selected values in this list but you may select them all before submit) or to create a map of values and submit it via javascript (for jQuery - $.post(url, data, callback)) or to add all pairs of name&value to some hidden element of a form and submit it.

Resources