在表单中添加模型,然后重新显示表单以添加更多

时间:2012-04-21 04:45:44

标签: asp.net-mvc-3

我是MVC3的新手,但到目前为止,我已经设法与我的代码相处得很好。

现在,我想创建一个简单的表单,允许用户输入表示员工姓名的文本字符串。然后,我希望将此表单提交并存储在我的模型中,列表中。然后应该重新显示表单,并使用for-each循环写出我已添加的名称。当我完成并继续前进时,我需要将此信息存储到我的数据库中。

我无法弄清楚的是,如何存储此临时信息,直到我将其推送到我的数据库。每次我提交我都可以做,但这引起了很多麻烦。

希望你们看到我正在尝试做的事情,并为它提供一个很棒的解决方案。 :)

这是我一直试图做的简化版本:

模型

public class OrderModel
{
    public virtual ICollection<Employees> EmployeesList { get; set; }

    public virtual Employees Employees { get; set; }
}

public class Employees
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }
}

查看

@model OrderModel
@{
    if (Model.EmployeesList != null)
    {
        foreach (var c in Model.EmployeesList)
        {
            @c.Name<br />
        }
    }
}
@using(Html.BeginForm())
{
    @Html.TextBoxFor(m => m.Employees.Name)

    <input type="submit" value="Add"/>
}

控制器

[HttpPost]
public ActionResult Index(OrderModel model)
{
    model.EmployeesList.Add(model.Employees);
    // This line gives me the error: "System.NullReferenceException: Object reference not set to an instance of an object."

    return View(model);
}

2 个答案:

答案 0 :(得分:1)

我认为这对 TempData 很有用。你可以在那里存储任何东西,有点像缓存,但与缓存不同,它只持续到下一个请求。要实现此功能,请更改此操作方法(仅限示例):

[HttpPost]
public ActionResult Index(OrderModel model)
{
    dynamic existingItems = TempData["existing"];
    if (existingItems != null) 
    {
        foreach (Employee empl in existingItems)
            model.EmployeesList.Add(empl );
    }
    model.EmployeesList.Add(model.Employees);
    TempData["existing"] = model.EmployeesList;
    return View(model);
}

答案 1 :(得分:1)

我认为您应该通过将员工列表刻录到页面来处理此问题。现在,您没有以任何方式识别列表。

在名为Employees的EditorTemplates文件中:

@model Employees

@Html.HiddenFor(m => m.ID)
@Html.HiddenFor(m => m.Name);

在您看来:

@using(Html.BeginForm())
{
    @Html.EditorFor(m => m.EmployeesList)
    @Html.TextBoxFor(m => m.Employees.Name)

    <input type="submit" value="Add"/>
}

[HttpPost]
public ActionResult Index(OrderModel model)
{
   if (model.EmployeesList == null)
      model.EmployeesList = new List<Employees>();

    model.EmployeesList.Add(model.Employees);
    return View(model);
}

作为此方法的额外奖励,添加ajax很容易,因此用户在添加新员工时永远不必离开页面(您可能只需使用javascript插入新的隐藏值并避免使用ajax。这取决于你是否做了除了在你的帖子中添加到你的列表之外的任何事情。)