3

I have form area in my view. If I click button A, I want to submit to /Books/1 and if I click button B, I want to submit to /Books/2

How do I achieve this with MVC?

4 Answers 4

3
<form id="form1" name="form1" action="/Books/" method="get">
<input type="text" name="search" value="">
<input type="submit" name="id" value="1">
<input type="submit" name="id" value="2">
</form>
1

It sounds like what you want to do is call the Books Controller, with, say, the Search action. So for instance you might want to call /Books/Search/<search expression>/1, or /Books/Search/<search expression>/2, etc. (There's a few different ways you could be formatting these URLs, but it's mostly a matter of personal preference I think) If you want the URLs to appear as you've got them above (without the action in the URL), that can be accomplished with routing, something like this:

routes.MapRoute(
    "Books",
    "Books/{searchExpr}/{pageId}",
    new { controller = "Books", action = "Search", searchExpr = "", pageId = 1 }
);

I think the main problem is that you're trying to use the WebForms PostBack everything paradigm in a situation where you're probably better off sending the information to the server in the URL or query string. The only time you're actually going to be posting form data here is when the user actually types something into the search box and clicks the Search button - at that point, the controller will pass the search expression to the appropriate View by stuffing it in ViewData, and from there, the View can pull it out and repopulate that textbox on the results page.

1
  • thanks everyone for their comments. I realized last night and while browsing around StackoverFlow using the Urls differently is the way to go. Going to take a little while to get my head away from thinking the web form way! Expect more questions soon! :)
    – Nick Swan
    Oct 29, 2008 at 10:54
1

MVC Views can have multiple forms on a 'page', so just create separate sections and give each one their own form action.

<form id="form1" name="form1" action="/Books/1" method="get">
<!--...form fields-->
</form>


<form id="form2" name="form2" action="/Books/2" method="get">
<!--...form fields-->
</form>
0

I have never seen the ability to have a form field attached to two forms, seems like it wouldn't work. What you can do is put a hidden field in the second form which, on submission, grabs the information from the textbox in the first form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.