In a lot of the MVC 3 examples that are available on the Internet today, they are quite typically strongly typed to a model, e.g. public ActionResult LogOn(LogOnModel model, string returnUrl).
This is extremely useful for the validation abilities and many other aspects; however, there are times when some or all of the data is not strongly typed; then what do you do? Read on for two different approaches.
There are a couple of different approaches to take:
Before we begin, here is an example of a strongly typed HttpPost example that we will change to not be.
To accomplish the first solution, the above example code could be altered as follows:
In the above example, Username and Password refer to the field names that would be assigned to the fields in the LogOn.cshtml view.
To accomplish the second solution, the above example could be altered as follows:
In the above example, Username and Password refer to the field names that would be assigned to the fields in the LogOn.cshtml view.
The FormCollection above can be accessed similarly to ViewData objects that are passed between views. As long as you know the field name, you can access it dynamically as seen above.
Whenever possible, I would always suggest to strongly type your code to a model because of the benefits it provides for clean validation and strongly typed views and controllers; however, in the rare instance that it simply won't work for you – the above two solutions provide simple alternatives. Published on Mar 17, 2019 Tags: ASP.NET MVC and Web API Tutorial
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
// code here
}
}
Solution One - Passing individual variables without a class
[HttpPost]
public ActionResult LogOn(string Username, string Password, string returnUrl)
{
// do some manual validation
}
Solution Two - Using the FormCollection
[HttpPost]
public ActionResult LogOn(FormCollection form, string returnUrl)
{
string Username = form["Username"];
string Password = form["Password"];
}
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.