C# ASP.NET MC3-创建记录和支持记录的单个接口
我有一个ASP.NET MVC3应用程序的开始,该应用程序应该实现调度。我的模型中包含以下内容:C# ASP.NET MC3-创建记录和支持记录的单个接口,c#,asp.net-mvc,asp.net-mvc-3,C#,Asp.net Mvc,Asp.net Mvc 3,我有一个ASP.NET MVC3应用程序的开始,该应用程序应该实现调度。我的模型中包含以下内容: public class Schedule { public int ScheduleID { get; set; } public bool isDisabled { get; set; } [DisplayName("For Delivery")] public bool isDeliver { get; set; } public int Count {
public class Schedule
{
public int ScheduleID { get; set; }
public bool isDisabled { get; set; }
[DisplayName("For Delivery")]
public bool isDeliver { get; set; }
public int Count { get; set; }
public virtual ICollection<TimeofDay> Times { get; set; }
public virtual Location Location { get; set; }
public int Week { get; set; }
public int weekday { get; set; }
}
public class TimeofDay
{
[Key]
public int TimeID {get;set;}
public DateTime Time { get; set; }
}
我的控制器将工作文件以接受传递的数据,直到我将数据添加到时间字段。这将在模型生成的TimeofDay表中创建新实体,并链接回ScheduleID。我不想用两个接口来输入这个简单的数据,但似乎找不到在一次操作中使用MVC3创建两个实体的方法。有人有什么想法吗
安德鲁
(谢谢你的阅读)
应要求,主计长:
public ActionResult Create(Schedule schedule, string[] schedTimes)
{
if (ModelState.IsValid)
{
Schedule newschedule = db.Schedule.Add(schedule);
db.SaveChanges();
return RedirectToAction("Index");
}
......
}
我现在意识到我需要创建一个视图模型,它将包含我的schedule类和一个字符串数组。我将创建时间表,然后遍历字符串数组,并创建TimeofDay对象,以便输入与times集合绑定。我们的表单字段需要有索引名称,如
Times[0].TimeID // this would probably be hidden field
Times[0].Time
Times[1].TimeID
Times[1].Time
.
.
Times[n].TimeID
Times[n].Time
执行此操作时,从中间删除行时可能会出现其他问题。有很多关于这个的博客帖子。Phil是我最喜欢的,因为它以非常简单的方式解释了如何为列表绑定使用非顺序索引。有关更多链接,请参阅我对的回答。我试图通过如下扩展模型来创建一个视图模型来支持这一点:
public class ScheduleCreate
{
public Schedule schedule {get;set;}
public string[] schedTimes {get;set}
}
然后,我通过更改以下内容修改了我的视图:
@model scheduler.Models.Schedule
致:
我另外将所有模型(参数)更改为model.schedule(参数)
然后我将控制器更改为:
public ActionResult Create(ScheduleCreate mod)
{
if (ModelState.IsValid)
{
Schedule newschedule = db.Schedule.Add(mod.schedule);
if (mod.schedTime != null)
{
foreach (string instanceTime in mod.schedTimes)
{
newschedule.Times.Add(new {Time = DateTime.Parse(instanceTime) }); // unteseted
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
PopulateDropDown();
return View(mod.schedule);
}
你能为你的
控制器添加代码片段吗?或者让它更具信息性?你是直接在你的控制器中使用实体框架还是DAL?!这不好,因为您创建了从MVC/UI层到DAL的依赖关系。请看我的回答:第一块代码在我的模型中,EF也是。有更好的方法吗?是的,这就是我昨晚在梦中想到的:我可能需要将它作为数组引用。我将对Javascript进行如下修改:newDivInput.name=“Times[”+GLOBAL_timeDivCount+“]”;事实证明,我应该为Schedule类使用一个构造函数,它将时间作为列表进行实例化。
@model scheduler.Models.ScheduleCreate
public ActionResult Create(ScheduleCreate mod)
{
if (ModelState.IsValid)
{
Schedule newschedule = db.Schedule.Add(mod.schedule);
if (mod.schedTime != null)
{
foreach (string instanceTime in mod.schedTimes)
{
newschedule.Times.Add(new {Time = DateTime.Parse(instanceTime) }); // unteseted
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
PopulateDropDown();
return View(mod.schedule);
}