简体   繁体   中英

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:

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

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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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