2010-08-13 81 views
3

我来自网络表单,对于MVC还很新。我想创建一个接触的形式,简单的邮件我的联系方式,MVC建筑电子邮件正文

如:

  • 名字
  • 电子邮件
  • 年龄
  • 公司

我需要收集大约十几个不同领域的信息离子。

在网页表单很容易建立电子邮件的主体只是通过调用TextBox.Text

什么是建在电子邮件主体除了具有在很长的屁股参数来传递的最佳方式:

[HttpPost] 
Public ActionResult Contact(string firstName, string lastName, string Email, int Age, string Company, ...) 
{ 
    // ... 
} 

先谢谢你。

回答

3
[HttpPost] 
Public ActionResult Contact(EmailMessage message) 
{ 
    // ... 
} 

和你的模型对象是这样的:

public class EmailMessage 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Email { get; set; } 
    .... 
} 

可以自动神奇地将其绑定到你的操作方法,如果你的表单元素匹配EmailMessage模型

<% using (Html.BeginForm()) { %> 
    First Name: <input type="text" id="FirstName" /> 
    Last Name: <input type="text" id="LastName" /> 
    Email <input type="text" id="Email" /> 
    .... 
<% } %> 

可以也可以通过用[DisplayName]和其他有用的MVC属性装饰你的模型属性来制作这个真棒。

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) %> 
<% } %> 
1

使用强类型视图,并使用HTML助手方法来构建表单。表单中的数据将在您的操作方法中的模型中提供给您。

+0

链接或视觉会有所帮助。谢谢。 – 2010-08-14 00:22:56

0

另一种方法(MVC 1)是接受一个FormCollection对象,并从中读取值,这可能更容易应用于已有的对象。

但我会用ThatSteveGuy的建议去做,并采用适当的MVC 2方式。