Sunday, March 27, 2011

multi form page issue in asp.net mvc

Inside a form for adding a category I am rendering a control that contains a second form for adding a subcategory. The category form's action is category/add while the inner form's action is ../addSubcategory. My problem is that when submitting the inner form, my Add action is called.

So, my question is this: how can i make my inner form fire action addSubcategory?

Any help would really be appreciated!

From stackoverflow
  • in case you're using AJAX to post, you could write your own js methods that fire on the click of the submit button, calling the correct action methods.

    in case you're not using AJAX, i would recommend separating the two forms in your markup, and then aligning the subcategory form inside the category form with css. use an empty div as a "spacer" in the category form, to make room for the subcategory form.

    semi-pseudo-example, to (hopefully) make it more clear what i mean:

    <form name="categoryForm" id="catForm" action="/Category/Add">
    <!-- some form elements here... -->
    <div id="subCategorySpacer">&nbsp</div>
    <!-- maybe some more form elements... -->
    <input type="submit">
    </form>
    
    <form name="subCategoryForm" id="subCatForm" action="/Category/addSubcategory">
    <!-- form elements here too. and a submit button -->
    </form>
    

    and then you move the subcategory form into the place where you have your spacer div, using css. naturally, this requires you to know the exact sizes of the forms, or to use javascript to resize them on the clientside.

  • I am concerned that you say "inner form." You can have two (or more) forms on a page, but you cannot nest them. This is probably what is causing your bug.

    With or without AJAX, you need to have two, separate forms on the page. I strongly recommend using an actual form, even with AJAX submission, because if you do not do this, you will not be able to gracefully fall back to regular form submission for users who have disabled JavaScript. The ASP.NET MVC Ajax.Form helper will take care of this for you. Make sure to test Request.IsAjaxRequest inside your controller action to determine whether to return JSON or a new View.

0 comments:

Post a Comment