为了使用MVC和
Linq to sql来解决一些基本问题,我正在努力改编Stephen Walther的
TaskList application:
我正在使用Steve Sanderson’s blog中描述的概念添加批量编辑系统.
这一切都按预期工作,但是,我在保存返回的任务列表时遇到问题.发布到我的BulkEdit循环返回列表并更新我的LinqTosql db任务列表中的每个项目.
我的BulkEdit视图继承了ViewPage< List< TaskList.Models.Task>>如下:
<% using (Html.BeginForm()) { %> <div id="items"> <% foreach (var task in ViewData.Model) { Html.RenderPartial( "TaskEditor",task,new ViewDataDictionary(ViewData) { {"prefix","tasks"} } ); } %> </div> <input type="submit" value="Save changes" /> <% } %>
TaskEditor控件继承System.Web.Mvc.ViewUserControl< Models.Task>看起来像这样:
<div> <%= Html.Hidden(ViewData["prefix"] + ".index",ViewData.Model.Id) %> <% var fieldPrefix = string.Format("{0}[{1}].",ViewData["prefix"],ViewData.Model.Id); %> <%= Html.Hidden(fieldPrefix + "Id",ViewData.Model.Id) %> Description: <%= Html.TextBox(fieldPrefix + "TaskDescription",ViewData.Model.TaskDescription)%> Date: <%= Html.TextBox(fieldPrefix + "EntryDate",ViewData.Model.EntryDate.ToString("o"))%> Completed: <%= Html.CheckBox(fieldPrefix + "IsCompleted",ViewData.Model.IsCompleted)%> </div>
Controller Get和Post方法如下:
[AcceptVerbs(HttpVerbs.Get)] public ActionResult BulkEdit() { var tasks = from t in db.Tasks orderby t.EntryDate descending select t; return View(tasks.ToList()); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult BulkEdit(IList<Task> tasks) { foreach(Task task in tasks) { foreach(Task dbTask in db.Tasks) { if (dbTask.Id == task.Id) { dbTask.TaskDescription = task.TaskDescription; dbTask.EntryDate = task.EntryDate; dbTask.IsCompleted = task.IsCompleted; } } } db.SubmitChanges(); return RedirectToAction("Index"); }
我的问题是,这似乎太复杂了,我还没有考虑从列表中添加或删除的任务.我更喜欢做的事情
db.Tasks = tasks;
并让Linq尽一切努力来解决哪些已经改变以及哪些是新的/旧的.
这可能吗?或者我很快就会期待Linq有点太过分了?