How to handle nested forms in ASP.NET MVC

2019-05-26 21:21发布

问题:

I'm trying to build a fairly complex form which as a couple of cascading selects - i.e. the user selects a value in one combo and the other combo is populated according to their first selection.

I've followed a tutorial on how to handle the cascading but the problem I have is that I now have nested forms (the code in the tutorial uses forms inside partial views to POST to a controller action to load the 2nd combo). I have my main form on which I want to collect the input values but also the nexted forms for the cascading select boxes. The problem I have is that the cascading selection doesn't post to the correct controller action, but instead posts to my main (outer) form's action.

I understand this is the correct behaviour for a browser (as nested forms apparently aren't supported) but what's the correct way to implement this?

回答1:

use this to have multiple submit buttons on one form which each have different controller actions to post to:

http://iwayneo.blogspot.co.uk/2013/10/aspnet-mvc-action-selector-with-list.html

as for cascading stuff - i would focus on populating these without Ajax 1st - then you can worry about adding this sort of flare - if it doesn't work without JS anyway you're in a bad place.

I would have the 1st dropdown populated when you initially load the form and have a "next" button to populate the next dropdown in the cascade. this submit can use the method above to post to an action which then populates the second data set based on the selection of the 1st dropdown.

make sense?

Then how you ajax that after the point is up to you but you'll have a very solid foundation to build up stuff like that as you will have it working in the minimal tech scenario.

w://



回答2:

The correct way is to only have one form. Then use AJAX to populate the cascading drop down list. The are 100s of examples online how to do this with JSON