1 通过Request接收数据,进行添加
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Register</title>
<script src="../../Scripts/jquery-1.7.1.min.js"></script>
</head>
<body>
<div>
<form method="post" action="/Home/AddClass">
班级名称<input type="text" name="txtClassName" value=" " />
创建时间<input type="datetime" name="txtCreateTime" value=" " />
<input type="submit" name="name" value="添加班级" />
</form>
</div>
</body>
</html>
public ActionResult AddClass()
{
ClassInfo classInfo = new ClassInfo();
classInfo.ClassName = Request["txtClassName"];
classInfo.CreateTime = Convert.ToDateTime(Request["txtCreateTime"]);
CodeFirstEntities db = new CodeFirstEntities();
db.ClassInfo.Add(classInfo);
if (db.SaveChanges()>0)
{
return Content("ok");
}
else
{
return Content("no");
}
}
2 将标签Name属性设定为跟类属性一致,可以直接以对象接收
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Register</title>
<script src="../../Scripts/jquery-1.7.1.min.js"></script>
</head>
<body>
<div>
<form method="post" action="/Home/AddClass">
班级名称<input type="text" name="ClassName" value=" " />
创建时间<input type="datetime" name="CreateTime" value=" " />
<input type="submit" name="name" value="添加班级" />
</form>
</div>
</body>
</html>
public ActionResult AddClass(ClassInfo classInfo)
{
CodeFirstEntities db = new CodeFirstEntities();
db.ClassInfo.Add(classInfo);
if (db.SaveChanges()>0)
{
return Content("ok");
}
else
{
return Content("no");
}
}
三 post方法添加数据
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Register</title>
<script src="../../Scripts/jquery-1.7.1.min.js"></script>
<script>
$(function () {
$("#btn").click(function () {
var pars = $("#frm").serializeArray();
$.post("/Home/AddClass", pars, function (data) {
alert(data);
});
});
});
</script>
</head>
<body>
<div>
<form method="post" action="/Home/AddClass" id="frm">
班级名称<input type="text" name="txtClassName" value=" " />
创建时间<input type="datetime" name="txtCreateTime" value=" " />
<input type="button" name="name" value="添加班级" id="btn"/>
</form>
</div>
</body>
</html>
public ActionResult AddClass()
{
ClassInfo classInfo = new ClassInfo();
classInfo.ClassName = Request["txtClassName"];
classInfo.CreateTime = Convert.ToDateTime(Request["txtCreateTime"]);
CodeFirstEntities db = new CodeFirstEntities();
db.ClassInfo.Add(classInfo);
if (db.SaveChanges()>0)
{
return Content("ok");
}
else
{
return Content("no");
}
}