Reputation: 520
I'm coming from web forms and still very new to MVC. I want to create a contact form that simply emails me the contact information,
e.g:
I need to collect about a dozen different fields of information.
In web forms it was easy to build the email body just by calling TextBox.Text
What's the best way to build the email body besides having to pass in a long-ass parameter:
[HttpPost]
Public ActionResult Contact(string firstName, string lastName, string Email, int Age, string Company, ...)
{
// ...
}
Thank you in advance.
Upvotes: 3
Views: 452
Reputation: 3807
You can consider using MvcMailer NuGet - it will greatly simplify your life. See the NuGet package at http://nuget.org/Packages/Search?packageType=Packages&searchCategory=All+Categories&searchTerm=mvcmailer and the project documentation at https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide
Hope it helps!
Upvotes: 0
Reputation: 63512
[HttpPost]
Public ActionResult Contact(EmailMessage message)
{
// ...
}
and your Model object looked like this:
public class EmailMessage
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
....
}
you can auto-magically bind it to your Action Method if your Form elements match the EmailMessage model
<% using (Html.BeginForm()) { %>
First Name: <input type="text" id="FirstName" />
Last Name: <input type="text" id="LastName" />
Email <input type="text" id="Email" />
....
<% } %>
you can also make this awesome-er by decorating your model properties with [DisplayName] and other useful MVC attributes.
public class EmailMessage
{
[DisplayName("First Name")]
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
....
}
<% using (Html.BeginForm()) { %>
<%: LabelFor(m => m.FirstName) %><%: EditorFor(m => m.FirstName) %>
<%: LabelFor(m => m.LastName) %><%: EditorFor(m => m.LastName) %>
<%: LabelFor(m => m.Email) %><%: EditorFor(m => m.Email) %>
<% } %>
Upvotes: 3
Reputation: 34408
The alternative (MVC 1) way is to accept a FormCollection
object and read the values out of that, which may be simpler to apply to what you've already got.
But I'd go with ThatSteveGuy's suggestion and do it the proper MVC 2 way.
Upvotes: 0
Reputation: 1095
Use a strongly typed view, and use your HTML helper methods to build the form. The data from the form will be available to you in the model in your action method.
Upvotes: 1