Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access my formcollection in action method ASP.NET mvc ?

Tags:

asp.net-mvc

I have form collection accessed in action method ,but how to get the value of it .I tried like this

string value = collection[1];

but I am not getting the value .How can I access the value in action method.

like image 592
michael Avatar asked Aug 09 '11 11:08

michael


People also ask

How do you pass data between action methods in MVC?

There are a number of ways in which you can pass parameters to action methods in ASP.NET Core MVC. You can pass them via a URL, a query string, a request header, a request body, or even a form. This article talks about all of these ways, and illustrates them with code examples.

What is the use of FormCollection in MVC?

FormCollection is one way of retrieving view data in controller. Depending on the type of value in input, you can parse its non-string value to string in the Action method.

How do you add value to FormCollection?

FormCollection collection = new FormCollection(); collection. Add("Name", "Value");


2 Answers

If you have:

<input type="text" name="inputName" />

You could use the attribute name of the element like below:

[HttpPost]
public ActionResult yourAction(FormCollection collection)
{
     string value = Convert.ToString(collection["inputName"]);
     ...
     return View();
}    
like image 143
German Blanco Avatar answered Oct 02 '22 14:10

German Blanco


I think you should attempt to stear clear of the formcollection object if you are able to, in favour of a strongly typed viewmodel. there are a few examples here on SO and i've linked the 1st one that I searched for:

passing FormCollection to controller via JQuery Post method and getting data back...

however, if you're keen to tie yourself in knots :), then here's an example iterating thro a formcollection:

http://stack247.wordpress.com/2011/03/20/iterate-through-system-web-mvc-formcollection/

like image 31
jim tollan Avatar answered Oct 02 '22 14:10

jim tollan