Retrieve form data in action method : ASP.NET MVC 3

2.2k Views Asked by At

I am trying to use a simple form with only a text field to get some information that will be used in an action method to redirect to a different action method. Here's the context:

I have a route mapped in my global.asax.cs file which prints "moo" the given amount of times. For example, if you typed "www.cows.com/Moo8", "Moo" would be printed 8 times. The number is arbitrary and will print however many "Moo"s as the number in the URL. I also have a form on the homepage set up as follows:

@using (Html.BeginForm("Moo", "Web"))
{
    <text>How many times do you want to moo?</text>
    <input type="text" name="mooNumber" />
    <input type="submit" value="Moo!" />
}

The number submitted in the form should be sent to the action method "Moo" in the "Web" controller (WebController.cs):

 [HttpPost]
        public ActionResult Moo(int mooNumber)
        {
            Console.WriteLine(mooNumber);
            return RedirectToAction("ExtendedMoo", new { mooMultiplier = mooNumber });           
        }

Finally, the "Moo" action method should send me back to the original "www.cows.com/Moo8" page; as you can see above I simply used an already existing action method "ExtendedMoo":

 public ViewResult ExtendedMoo(int mooMultiplier)
        {
            ViewBag.MooMultiplier = RouteData.Values["mooMultiplier"];

            return View();
        }

How can I access the value submitted in my form and use it in the last call to "ExtendedMoo"?

4

There are 4 best solutions below

5
On

Refer to this post or this, you might get some idea how routing works. Something is wrong with "www.cows.com/Moo8", try to find it out. Hint "{controller}/{action}/{parameter_or_id}"

6
On

Instead of RedirectToAction, use Redirect and create the Url. This should do the trick:

return Redirect(Url.RouteUrl(new { controller = "Web", action = "ExtendedMoo", mooMultiplier = mooNumber }));

I hope i helps.

0
On

If I understood right

You can you use form Collection to get the value from textbox.

Make Sure the input tag has both id and name properties mentioned otherwise it wont be available in form collection.

    [HttpPost]
    public ActionResult Moo(int mooNumber, **formcollection fc**)
    {
        **string textBoxVal= fc.getvalue("mooNumber").AttemptedValue;**
        Console.WriteLine(mooNumber);
        return RedirectToAction("ExtendedMoo", new { mooMultiplier = mooNumber });           
    }
0
On

Oh wow. Turns out that form was on my Homepage, so instead of using "Moo" as the action method, I needed to override the "Homepage" action method with a [HttpPost] annotation over THAT one. Didn't realize that forms submitted to the page they were rendered from - that was a really useful piece of information in solving this problem!

Thanks all for your attempts at helping out!