如何为待办事项列表应用程序设计 ViewModel?
我正在创建一个简单的待办事项应用程序,它有两个实体,任务
和类别
。
要创建任务
,必须选择类别
。为此,我想我需要一个 ViewModel。
这是任务实体
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; }
}
这是类别实体
public class Category
{
public int categoryId { get; set; }
public string categoryName { get; set; }
}
如何设计一个 TaskCategoryViewModel
以便我可以在 CreateTask
视图中绑定 category
?
编辑:我使用经典的 ADO.NET,而不是实体框架或 LINQ to SQL。
I am creating a simple todo application which has two entities, tasks
and categories
.
To create a task
, choosing a category
is a must. For this, I figured I would need a ViewModel.
Here is the Task entity
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; }
}
Here is the Category entity
public class Category
{
public int categoryId { get; set; }
public string categoryName { get; set; }
}
How can I design a TaskCategoryViewModel
so that I can bind the category
in the CreateTask
view?
Edit: I am using classic ADO.NET instead of Entity Framework or LINQ to SQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Kishor,
最好的选择是拥有一个模型,该模型可以定义您的任务和类别(全部合一),
这就是所有内容如何结合在一起的。
其中
用于创建下拉列表,准备使用
这将为您创建漂亮的下拉列表
Kishor,
the best bet is have model that hods definition for your task and for category (all in one)
here is how everything hangs together.
where
is used for creating drop down list which is ready to use
this will create you nice dropdown list
在 TaskViewModel (我更喜欢将其命名为 CreateTaskViewModel)中,为类别选择列表创建属性
在控制器中,在返回视图之前绑定该属性(请注意,当 ModelState 无效时,这也应该在后处理程序中完成)
最后,在视图中
< strong>编辑:
在您的代码中,
_repository.AllCategories()
应替换为您的数据访问代码,该代码返回具有类型的对象IEnumerable<类别>
。实际上,您使用哪种数据访问技术并不重要。并且不要忘记将using System.Linq;
语句添加到控制器文件中(如果缺少)。In the TaskViewModel (I would prefer naming it CreateTaskViewModel) create property for categories select list
In controller, bind that property before returning view (note that this also should be done in post handler, when ModelState is invalid)
And finally, in the view
Edit:
In your code,
_repository.AllCategories()
should be replaced by your data access code, that returns object having typeIEnumerable<Category>
. It actually does not matter which data access technology you use. And do not forget to add theusing System.Linq;
statement to your controller file, if it's missing.