MVC 3 Maintain an Order on a List<> property from an entity
I am running into issue with a project I am working on. I have a Task Scheduler. The models consists of Jobs and Tasks. Job and Task have a many to many relationship. I maintain the relationship to task in Job through a List Tasks property. I want the user to be able to arrange the List of Tasks in a specific order, so that I can execute them in a precise manner. I constructed methods for ordering the tasks, but the code first framework always maintains the relationship in a order based on ID. Thus, the order is lost. Does anyone have idea of how to implement something like this in MVC 3?
#region
JobModel
public class Job
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime? Date { get; set; }
public int JobCate开发者_开发问答goryID { get; set; }
public virtual JobCategory JobCategory { get; set; }
public virtual List<Task> Tasks { get; set; }
}
#endregion
#region TaskModel
public class Task
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
}
While explicitly for MVC2, I have found this article and code within Mvc Nested List Tutorial to be extremely helpful.
I have used it to do exactly what you are describing by embedding the sort order in the model of the class and sorting on in during the view.
You should be able to create javascript or other actions to reorder and adjust the hidden sort values for each element. Then after the post each element should be correctly sorted.
Good Luck
Ok for those out there interested in a working solution.
I first removed the many to many relationship between the two models Task and Job. I have learned that many to many relationships in MVC can get complicated for complex Datasets. So I recommend avoiding this relationship whenever possible. I then created a partial view with tasks that could dynamically be loaded into the Job/Edit controller. I passed to the view a job.Tasks.OrderBy(m = m.order) as recommended above by @William Bonar.
As tasks are added, I increment the order attribute of the last task by 1 and add to the Tasks list. I then provide a jquery/ajax interface for users to move the tasks up and down in the list, which uses some pretty simple logic to adjust order among tasks.
Hope this helps some people out.
精彩评论