基肖尔,
最好的选择是拥有为您的任务和类别定义的模型(一体化)
这里是一切如何挂在一起。
哪里
IEnumerable Categories用于创建可供使用的下拉列表
model.NewTask.categoryId, Model.Categories) %>这将创建一个很好的下拉列表
private IEnumerable GetCategories
{
get
{
List categories = new List
{
new Category() {categoryId = 1, categoryName = "test1"},
new Category() {categoryId = 2, categoryName = "category2"}
};
return categories;
}
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult CreateTask()
{
TaskModel taskModel = new TaskModel();
LoadCategoriesForModel(taskModel);
return View(taskModel);
}
private void LoadCategoriesForModel(TaskModel taskModel)
{
taskModel.Categories =
GetCategories.Select(
x =>
new SelectListItem()
{Text = x.categoryName, Value = x.categoryId.ToString(CultureInfo.InvariantCulture)});
}
public ActionResult CreateTask(TaskModel taskModel)
{
if (ModelState.IsValid)
{
// do your logic for saving
return RedirectToAction("Index");
}
else
{
LoadCategoriesForModel(taskModel);
return View(taskModel);
}
}
///
/// your model for creation
///
public class TaskModel
{
public Task NewTask { get; set; }
public IEnumerable Categories { get; set; }
}
///
/// Task
///
public class Task
{
public int taskId { get; set; }
public int categoryId { get; set; }
public string taskName { get; set; }
public bool isCompleted { get; set; }
public DateTime creationDate { get; set; }
public DateTime completionDate { get; set; }
public string remarks { get; set; }
public string completionRemarks { get; set; }
}
///
/// Category
///
public class Category
{
public int categoryId { get; set; }
public string categoryName { get; set; }
}