如何对包含另一个实体列表的实体进行模型绑定?

时间:2018-01-07 20:53:44

标签: c# asp.net-mvc

我想使用包含另一个实体列表的模型制作表单,但我不知道该怎么做。注意:没有实体框架。

我只使用一个只包含其字段的模型,而不是另一个实体。

我的代码是:

Tarea.cs

public class Tarea
{
    public int ID { get; set; }
    public string NombreTarea { get; set; }
    public int TiempoTarea { get; set; }
}

Employee.cs

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime JoiningDate { get; set; }
    public int Age { get; set; }
    public List<Tarea> Tareas { get; set; }
}

我的观点是:

Create.cshtml

@model MVCSimpleApp.Models.Employee
....
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Employee</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.JoiningDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.JoiningDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.JoiningDate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

我不知道如何将List<Tarea>放在表单中。提前谢谢。

1 个答案:

答案 0 :(得分:1)

例如,如果我们想要收集两组Tareas模型,

查看代码:

@for (var item = 0; item < 2; item++)
{
  @Html.HiddenFor(model => model.Tareas[item].ID)
  @Html.TextBoxFor(model => model.Tareas[item].NombreTarea, new { @class = "form-control" })
  @Html.TextBoxFor(model => model.Tareas[item].TiempoTarea, new { @class = "form-control" })
}

并在Post Create Action Method ..

[HttpPost]
public ActionResult Create(Employee model)
{
  // here we we get the all values given from the view ...
  string example = model.Name;
  List<Tarea> list = model.Tareas; // and iterate through model.Tareas to get List model values
}