ASP.NET MVC2.0 基础教程 实现CRUD操作

这个演示项目实现了CRUD增删查改操作。

开发环境:Visual Studio 2010 + Linq To Sql + SQL Server 2005

一、Demo演示

1、下载本演示Demo源码:https://files.cnblogs.com/rubyloveromantic/MyMikeDemo.rar

2、Visual Studio 2010打开本演示项目,运行即可。

二、从头开始建立这个演示项目

1、附加下载的Demo源码中的数据库:mike108mvp.mdf 【ok】
2、新建一个MVC Preview应用程序,在Models目录下,添加一个Linq To Sql文件:Mike108mvp.dbml,将数据库中的User表拖入LinqToSql设计窗口中。【ok】
3、web.config中添加命名空间:【ok】
4、在相关目录创建视图文件【ok】


5、Controllers/Users/目录下,新建一个UsersController.cs文件,输入增删查改代码。【ok】

 

usersControl
public class UsersController : Controller
{
Mike108mvpDataContext db
= new Mike108mvpDataContext();

#region CRUD操作
public ActionResult List()
{
List
<User> model = db.User.ToList();
return View(model);
}

public ActionResult Create()
{
return View();
}

[HttpPost]
public ActionResult Add()
{
User model
= new User();
model.UserId
= 0;
UpdateModel(model, Request.Form.AllKeys);
db.User.InsertOnSubmit(model);
db.SubmitChanges();

return RedirectToAction("List");
}
public ActionResult Details(int userID)
{
User model
= db.User.FirstOrDefault(e => e.UserId == userID);
return View(model);
}
public ActionResult Edit(int userID)
{
User model
= db.User.FirstOrDefault(e => e.UserId == userID);
return View(model);
}

[HttpPost]
public ActionResult Edit(int userID, string parm)
{
if (parm == "更新")
{
User model
= db.User.FirstOrDefault(e => e.UserId == userID);
UpdateModel(model, Request.Form.AllKeys);
db.SubmitChanges();
}
return RedirectToAction("List");
}
public ActionResult Delete(int userID)
{

User model
= db.User.FirstOrDefault(e => e.UserId == userID);
db.User.DeleteOnSubmit(model);
db.SubmitChanges();

return RedirectToAction("List");
}
#endregion

#region 数据重置

public ActionResult DataReset()
{
//批量删除
List<User> oldList = db.User.ToList();
db.User.DeleteAllOnSubmit(oldList);

//批量添加
List<User> newlist = new List<User>
{
new User { UserName = "孙中山", Age = 53, Career = "中国总统" },
new User { UserName = "蒋中正", Age = 36, Career = "中国总统" },
new User { UserName = "小布什", Age = 61, Career = "美国总统" },
new User { UserName = "列宁", Age = 49, Career = "邪恶苏联" },
new User { UserName = "斯大林", Age = 49, Career = "邪恶苏联" },
new User { UserName = "比尔盖茨", Age = 62, Career = "微软老大" },
new User { UserName = "Scott Guthrie", Age = 33, Career = "ASP.NET Leader" }
};
db.User.InsertAllOnSubmit(newlist);
db.SubmitChanges();
return RedirectToAction("List");
}
#endregion
}

注:该教程是在学习Mike In Jesus课程是对他的代码作的升级(to MVC2.0)。 无侵权之意。

posted @ 2010-08-05 19:23  宝石蓝  阅读(6732)  评论(10编辑  收藏  举报