【发布时间】:2015-01-08 21:17:15
【问题描述】:
我有一个项目,我需要有两个项目列表 A、B、C、D 和 1、2、3、4 等,并且这个列表将有一个 CRUD 界面来随着时间的推移更改列表(通常只添加到列表中)。
然后在一个页面上,我有一个数据条目,最终用户将在其中看到两个带有复选框的列表,以便他们可以选择该列表中的哪个适用于该条目。所以他们可以从第一个列表 A、D 和第二个 2,4 中进行选择。我需要将此选择与页面上的其他条目(例如名称、注释、区域等)一起存储。
我的问题是,对于 MVC 和 EF,我在数据库中有一个模型和表以及两个列表的 CRUD,我什至设计了我的数据输入页面但是当单击保存按钮时我不确定如何最好地存储和持久化这些数据。
我不确定我是否已经完全描述了这一点,但我需要一个列表来保存每个列表的可能选择,然后在输入数据后将条目的选择保存回数据库。
我希望这是有道理的,如果我有代码我会发布,但我仍处于设计阶段,所以我所拥有的是废话,因此使用了大删除键,我正在开始一个新的寻找想法。
谢谢
悬崖。
[编辑]
我想我想说的是我想要页面上有两个多选列表并存储这两个列表中的选择。但列表中的值也来自数据库。
[编辑]
好吧,看来我找到了一个可以处理列表的插件,实际上非常适合我的需求
只需要弄清楚如何将其中两个列表放在一个视图上,这应该不会太难。
{编辑}
好的,一直在努力解决这个问题,并将以下内容作为我的模型...
public class CallResult
{
[Key]
public int CallResultId { get; set; }
public string Area { get; set; }
public string Number { get; set; }
public DateTime Date { get; set; }
public ICollection<TargetCustomer> TargetCustomers { get; set; }
}
public class TargetCustomer
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<CallResult> CallResults { get; set; }
}
我需要一个包含多个 TargetCustomers 的创建页面,然后将用户选择的内容作为列表的一部分存储在 CallResult 中。
到目前为止我的创建操作是:
public ActionResult Create()
{
var targetCustomers = new List<TargetCustomer>()
{
new TargetCustomer() { Id = 1, Name = "Manger", CallResults = new Collection<CallResult>()},
new TargetCustomer() { Id = 2, Name = "Worker", CallResults = new Collection<CallResult>()},
};
ViewBag.MultiSelectTC = new MultiSelectList(targetCustomers, "Id", "Name");
return View();
}
视图中的 sn-p:
<div class="form-group">
<div class="control-label col-md-2">
<label>Target Customer</label>
</div>
<div class="col-md-10">
@Html.ListBox("targetCustomers", (MultiSelectList)ViewBag.MultiSelectTC)
</div>
</div>
现在我只需要将数据返回到 Action 中,这样它就可以针对 EF 数据库中的 CallResult 进行存储,我有这个:
public ActionResult Create([Bind(Include = "CallResultId,Area,Number,Date")] CallResult callResult, int[] targetCustomers)
{
if (ModelState.IsValid)
{
// Find Tag from Database
// Attach tag entity to Post
foreach (var custId in targetCustomers)
{
var cust = db.TargetCustomer.Find(custId);
callResult.TargetCustomers.Add(cust);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(callResult);
}
但是当它到达 callResult.TargetCustomers.Add(cust); 时,我得到了 Null Ref 的异常;行。
我希望这一切比我昨晚的胡言乱语更有意义,感谢您的帮助...
【问题讨论】:
标签: c# asp.net-mvc entity-framework list model-view-controller