How to handle form data

Let's say that you have this form:

<form method="post" action="/user/index/">

FirstName:<br />
<input type="text" name="FirstName" /><br />

LastName:<br />
<input type="text" name="LastName" /><br />

<input type="submit" /><br />
<br />

And this class:
    class User
        /// <summary>
        /// Gets or sets first name.
        /// </summary>
        public string FirstName { get; set; }

        /// <summary>
        /// Gets or sets last name.
        /// </summary>
        public string LastName { get; set; }

How can you easily load data into the class? Well, it's easy:

        public IActionResult IndexPost()
            User user = new User();
            PropertyAssigner.Assign(user, Parameters);

            // Store object in your database.

            return Redirect("/user/index/");

Just two lines of code. You could add error handling too, Assign throws a PropertyException which contains a list of all properties and why they couldn't be assigned with the form data.

Last edited Feb 10, 2010 at 12:04 PM by jgauffin, version 2


No comments yet.