本教程用到的编程软件为VS2015社区版
新建项目
新建项目,选中Visual C#
- windows
- web
- asp.net web 应用程序
,这里使用的是默认名称
添加数据库
选中引用下的App_Data文件夹,右键
-添加
-类
新建数据库,选中Visual C#
- web
-数据
-SQL server 数据库
,这里使用的是默认名称
在数据库中添加表
鼠标左键双击,跳转到服务器资源管理器
选中表,右键添加新表
在下方设计编辑框输入下列代码
CREATE TABLE [dbo].[Table] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[randoms] NVARCHAR (MAX) NULL,
[length] INT NULL,
[pv] DECIMAL (18) NULL,
[run] BIT NULL,
[runtest] BIT NULL,
[inputtime] DATETIME NULL,
[comm] NVARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Table]
这行代码中的Table为表的名称,这里使用的是表的默认名称Table
点击左上角更新
,再点更新数据库
点击服务器资源管理器中左上角刷新图标
添加模型类
新建模型类,选中Models文件夹,右键
-添加
-类
新建模型类,选中Visual C#
- web
-数据
-LINQ to SQL类
,这里使用的是默认名称
打开服务器资源管理器
选中刚刚新建的表Table,拖到右边空白位置
添加控制器
新建控制器,选中Controllers文件夹,右键
-添加
-控制器
新建控制器,这里使用的是默认名称DefaultController.cs
DefaultController.cs中包含的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Models;
namespace WebApplication2.Controllers
{
public class DefaultController : Controller
{
private DataClasses1DataContext db = new DataClasses1DataContext();//DataClasses1,模型名称
// GET: Default
public ActionResult Index()
{
var lists = from t in db.Table //Table,表名称
orderby t.Id
descending
select t;
return View(lists.ToList());
}
// GET: Default/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Default/Create
public ActionResult Create()
{
return View();
}
// POST: Default/Create
[HttpPost]
public ActionResult Create(Table collection) //Table,表的名称
{
try
{
// TODO: Add insert logic here
Table newlist = new Table();
newlist.randoms = collection.randoms;
newlist.length = collection.length;
newlist.run = collection.run;
newlist.runtest = collection.runtest;
newlist.comm = collection.comm;
newlist.inputtime = DateTime.Now;
db.Table.InsertOnSubmit(newlist);
db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Default/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Default/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Default/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Default/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
添加视图
public ActionResult Index()
选中这行代码中的Index,右键
-添加视图
模板选择List,模型类选择前面新建的表的名称,这里表的名称为Table
跳转到视图界面后,点击运行出现的界面
返回前面控制器的代码页
public ActionResult Create(Table collection) //Table,表的名称
选中这行代码中的Create,右键
-添加视图
模板选择Create,模型类选择前面新建的表的名称,这里表的名称为Table
跳转到视图界面后,点击运行出现的界面