BeginCollectionItem无法绑定部分值

时间:2016-03-01 20:37:47

标签: c# .net asp.net-mvc collections

我在做Editing a variable length list, ASP.NET MVC 2-style教程,但我无法将ViewModel的值绑定到我的创建视图

型号:

 public class WebPages
{
    [Key]
    public int WebPagesId { get; set; }

    public String DomainName { get; set; }

    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime DomainStart { get; set; }

    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime DomainExp { get; set; }
    public String DomainEmails { get; set; }
    public String DomainUsers { get; set; }
    public String DomainPasswords { get; set; }

}
}

视图模型:

public class WebPagesViewModel
{
    [Key]
    public int Id { get; set; }
    public String DomainName { get; set; }

    public class Domain
    {
        public String DomainEmails { get; set; }
        public String DomainUsers { get; set; }
        public String DomainPasswords { get; set; } 
    }
    public List<Domain> Domains { get; set; }
}
}

创建GetController

 public ActionResult Create(WebPages model)

    {

     var ejemdata =  new List<WebPagesViewModel.Domain>
        {
            new WebPagesViewModel.Domain
            {
                DomainEmails = "email@gmail.com",
                DomainUsers = "Testuser",
                DomainPasswords = "testpassword"
            }
        };

        var vm = new WebPagesViewModel
        {
            Clients = new SelectList(db.ClientsList, "ClientsId", "ClientsName"),
          Domains = ejemdata
        };


        return View(vm);
    }

创建视图:

 @foreach (var item in Model.Domains)
        {

            { Html.RenderPartial("_WebPagesPartial", item);} 

        }

部分:

 @using xxx.Models.ViewModels
 @model WebPagesViewModel.Domain
@using HtmlHelpers.BeginCollectionItem

 <h2>Partial View</h2>

 <div>
@using (Html.BeginCollectionItem("Domains"))
{

        Html.EditorFor(x => x.DomainPasswords);
        Html.EditorFor(x => x.DomainUsers);
        Html.EditorFor(x => x.DomainEmails);
}

我使用断点调试,控制器从我的ejemdata获取值,并将其传递到我的创建视图foreach

Receiving data in View photo

因此,当页面加载时,它只从部分加载标签,但不显示BeginCollectionItem方法中的任何内容,我在HTML上得到这个

HTML:

<input type="hidden" name="Domains.index" autocomplete="off" value="28f4e8e7-cde3-44fe-a739-b4c8acb15ec2">

1 个答案:

答案 0 :(得分:0)

您使用

Html.EditorFor(x => x.DomainPasswords);

只调用方法但不输出结果。您需要将其更改为

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

(和其他2个HtmlHelpers同上)