2010-08-13 59 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方式。