简体   繁体   English

ASP.NET MVC表单模型

[英]ASP.NET MVC Form Models

I have a form that consists of rows similar to this: 我有一个包含类似于以下内容的行的表单:

@model  Models.Group

@using (Html.BeginForm("Test", "CreateGroup", FormMethod.Post))
{
<form method="post">

<div class="row" id="user2">
    <div class="col-md-3">
        @Html.TextBoxFor(m => m.UserName_2, new { @class = "form-control" })

    </div>
    <div class="col-md-3">
        @Html.TextBoxFor(m => m.UserEmail_2, new { @class = "form-control", @type = "email" })
    </div>
</div>
<div class="col-md-12">
    &nbsp;
</div>
<div class="row" id="user3">
    <div class="col-md-3">
        @Html.TextBoxFor(m => m.UserName_3, new { @class = "form-control" })

    </div>
    <div class="col-md-3">
        @Html.TextBoxFor(m => m.UserEmail_3, new { @class = "form-control", @type = "email" })
    </div>
</div>
<div class="row">
   <div class="col-md-12">
      <button type="submit" class="btn btn-success btn-lg margin-right">
      <span class="glyphicon glyphicon-save"></span> Save
      </button>
   </div>
  </div>
</form>
}

With a model that currently looks like this: 使用当前看起来像这样的模型:

public class Group
{
    public int Id { get; set; }

    public string UserName_2 { get; set; }

    public string UserEmail_2 { get; set; }

    public string UserName_3 { get; set; }

    public string UserEmail_3 { get; set; }
}

How do I get my View to support something like this where I can be able to add more Users without having to hard code the values into my Group model: 如何使我的View支持类似这样的功能,使我能够添加更多用户而不必将值硬编码到我的Group模型中:

public class Group
{
    public int Id { get; set; }

    public List<User> Users { get; set; }
}

public class User
{
    public string Name { get; set; }

    public string Email { get; set; }
}

Edit: Or is there a better way to send the information from my form to the controller than using a Model? 编辑:或者比使用模型有更好的方法将信息从表单发送到控制器? I was trying to use FormCollection but that doesn't seem to have any data when I submit 我正在尝试使用FormCollection,但提交时似乎没有任何数据

Try accessing users by index, model binding should pick it up. 尝试按索引访问用户,模型绑定应将其选中。 The code would look like: 代码如下所示:

@for(int i = 0; i < Model.Users.Length; i++)
{
<div class="row">
    <div class="col-md-3">
        @Html.TextBoxFor(m => Model.Users[i].Name, new { @class = "form-control" })

    </div>
    <div class="col-md-3">
        @Html.TextBoxFor(m => Model.Users[i].Email, new { @class = "form-control", @type = "email" })
    </div>
</div>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM