版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cxh6863/article/details/83472465
1、在主界面Index.cshtml添加“添加”的链接
<tr>
<td colspan="4"> @Html.ActionLink("添加", "Add", "Home") @Html.ActionLink("返回", "Index", "Home")</td>
</tr>
2、HomeController
2.1显示添加
[HttpGet]
public ActionResult Add()
{
return View();
}
2.2执行添加
[HttpPost]
public ActionResult Add1()
{
try
{
//DbEntityEntry<BlogUser> entry = db.Entry<BlogUser>(blogUser);
BlogUser user = new BlogUser();
user.Id = int.Parse(Request["id"]);
user.Name = Request["name"];
user.State =bool.Parse(Request["state"]);
ViewData.Model = user;
//db.BlogUser.Attach(user);
db.BlogUser.Add(user);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
catch (Exception ex)
{
return Content("添加失败," + ex.Message);
}
}
3、Add.cshtml
@using (Html.BeginForm("Add1", "Home", FormMethod.Post))
{
<table id="tbList">
<tr>
<td colspan="2">添加</td>
</tr>
<tr>
<td>账号:</td>
<td><input type="text" id="id" name="id" /></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" id="name" name="name" /></td>
</tr>
<tr>
<td>状态:</td>
<td><input type="text" id="state" name="state" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="确认添加" />@Html.ActionLink("返回", "Index", "Home")</td>
</tr>
</table>
}
其中name很关键,在controller中通过name来用request获取输入的值
布局代码
<title>添加</title>
<style type="text/css">
#tbList {
border: 1px solid #0094ff;
width: 400px;
margin: 10px auto;
border-collapse: collapse;
}
#tbList th, td {
border: 1px solid #0094ff;
padding: 10px;
}
</style>