如何使用对象列表创建多个文本框

时间:2012-03-22 13:42:02

标签: asp.net-mvc razor

大家好,我必须创建一个共享页面,我有一个要分享的contentitem,分享它的用户和他想与之分享的用户的收件人,但我想动态,这是我的域模型

public class ShareContentItemModel : BaseModel
{
    public ContentItem ContentItem { get; set; }
    public User User { get; set;}

    [Display(Name = "Recipients")]
    public List<Recipient> Recipients { get { return new List<Recipient> { new Recipient { Name = "Recipient name here", Email = "Write Recipient Email here" } }; } }

    [Required]
    [Display(Name = "Nachricht")]
    public string Message { get; set; }
}

public class Recipient{
    [Display(Name = "Recipient Name:")]
    public string Name  { get; set;}
    [Display(Name = "Recipient Email Address:")]
    public string Email { get; set;}
}

这是我的观点

 @using (Html.BeginForm("Submit", "Contact", FormMethod.Post))
 { 
 <p>Hi: @Html.DisplayTextFor(m=>m.User.Salutation) @Html.DisplayTextFor(m=>m.User.Firstname) @Html.DisplayTextFor(m=>m.User.Lastname)</p>            
<table border="0" style="padding:5">
    <tr>
        <td class="editor-label">@Html.LabelFor(m => m.ContentItem.Title): </td>
        <td class="editor-field">@Html.DisplayTextFor(m => m.ContentItem.Title)
            <div>@Html.ValidationMessageFor(m => m.ContentItem.Title)</div>  
        </td>
    </tr>
    <tr> 
        <td class="editor-label">@Html.LabelFor(m => m.ContentItem.Description): </td>
        <td class="editor-field">@Html.DisplayTextFor(m => m.ContentItem.Description)
            <div>@Html.ValidationMessageFor(m => m.ContentItem.Title)</div>  
        </td>
    </tr>
    <tr><td colspan="2">Recipients:</td></tr>
    @foreach (var item in @Model.Recipients)
    {
    <tr>
        <td>@item.Name: @Html.TextBoxFor(/*Dont know what to put in here*/)</td>
        <td>@item.Email: @Html.TextBoxFor(/*Dont know what to put in here*/) </td>
    </tr>    
    }
    <tr>
        <td>   <a class="small button" href="#">Add Recipient:</a> </td>
        <td><input type="submit" class="button med primary" style="float: right;" value="ABSENDEN" /></td>
    </tr>
</table>

 }   

你可以在//中看到这里不知道要放什么 我不能使用item.name或item.email属性,你可以帮我这个

Pd积。对象很好,cshtml渲染正常,我只需创建此文本框即可开始创建更多收件人。

非常感谢

1 个答案:

答案 0 :(得分:3)

行。所以这就是你如何做到的。您可以创建编辑器模板并使用它。

步骤1)创建一个名为&#34; EditorTemplates&#34;的文件夹。在您的View / yourViewFolderName

步骤2)创建名为Receipent.cshtml

的视图

enter image description here

将此代码添加到该文件

@model YourNameSpace.Models.Recipient
<p>
   @Html.EditorFor(x=>x.Name) : @Html.TextBoxFor(x=>x.Name)
</p>
<p>
   @Html.EditorFor(x=>x.Email) : @Html.TextBoxFor(x => x.Email)
</p>

步骤3)在主视图中,只需调用编辑器模板而不是foreach循环代码

@Html.EditorFor(x=>x.Recipients)

这应该可以正常工作。我测试了你的模型。

保持编辑器模板名称与要在foreach中显示的属性名称相同。 MVC将负责其余的工作。

相关问题