写在前面
前面我们已经搭建好了项目,这一小节我们使用Dapper 中的事务实现一对多的添加操作。
问题描述
在做添加的时候很头疼需要从页面传递一组数据到后台,但同时又需要传递几个独立的参数。
以前的做法是在后台分别接收不同参数的Json,然后转成DataTable循环遍历解析获取值最后执行添加操作。
但是,个人觉得这样做太麻烦。于是,在网上搜了一下,看看有没有更简单的方法。
发现有的建议传字符串后台格式化或解析也有专门写一个切面程序修改mvc自带的格式化方法的等等。
但是,都不是我想要的简单的方法。直至,后来我发现以下的写法。
解决方法
- 因为是一对多的添加,所以,需要在sys_Book_Type实体类中添加泛型的sys_Borrow_Book
public List<sys_Borrow_Book> books { get; set; }
- 前台拼接Json对象
var bookType = { book_Type_Name: "" + $("#book_Type_Name").val() + "", book_Type_Des: "" + $("#book_Type_Des").val() + "", books: [] };
var tr = $("#tab tr:gt(0)");
for (var i = 0; i < tr.length; i++) {
var td = $(tr[i]);
var aa = td.children().children().val();
var bb = td.children().next().children().val();
var cc = td.children().next().next().children().val();
bookType.books.push({ book_Num: "" + aa + "", book_Name: "" + bb + "", book_Desc: "" + cc + "" });
}
- 通过ajax发送给后台接收
$.ajax({
url: "../BorrowBook/Adds_Op",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(bookType)
}).done(function (msg) {}).fail(function (e) { });
注意:
在前台发送post请求时,要让后台能接收到前台发送的数据,必须在ajax里加上 contentType: "application/json",
和data: JSON.stringify(bookType)
。如果,没有加的话。后台有可
以接收不要参数。
- 后台接收Json对象
/// <summary>
/// 执行一对多的数据添加
/// </summary>
/// <param name="Jsons">前台接收的Json</param>
/// <returns>成功返回1,失败返回0</returns>
[HttpPost]
public int Adds_Op(sys_Book_Type Jsons)
{
//接收表1数据
var Id = Guid.NewGuid().ToString();
sys_Book_Type bty = new sys_Book_Type { };
bty.book_Type_id = Id;
bty.book_Type_Name = Jsons.book_Type_Name;
bty.book_Type_Des = Jsons.book_Type_Des;
bty.create_Time = DateTime.Now;
//接收表2数据
var Jsonbook = Jsons.books;
List<sys_Borrow_Book> listbooks = new List<sys_Borrow_Book> { };
foreach (var item in Jsonbook)
{
sys_Borrow_Book bk = new sys_Borrow_Book();
bk.book_Id = Guid.NewGuid().ToString();
bk.book_Num = item.book_Name;
bk.book_Name = item.book_Name;
bk.book_Desc = item.book_Desc;
bk.borow_Time = DateTime.Now;
bk.book_Type_id = Id;
bk.user_Id = "ba33a34eb98411e9870700155d08c915";
listbooks.Add(bk);
}
//执行添加操作
//此处省略两三行代码
//最后返回执行结果
return result;
}
具体实现
- 在 Controller文件夹创建BorrowBookController类
- 在 BorrowBookController 控制器中 创建 *Add 视图
/// <summary>
/// 创建添加视图
/// </summary>
/// <returns></returns>
public ActionResult Add()
{
return View();
}
- 在 BorrowBookController 控制器中 创建 Adds_Op 执行添加方法
/// <summary>
/// 执行一对多的数据添加
/// </summary>
/// <param name="Jsons">前台接收的Json</param>
/// <returns>成功返回1,失败返回0</returns>
[HttpPost]
public int Adds_Op(sys_Book_Type Jsons)
{
int result = 0;
var para = new List<Tuple<string, object>>();
Tuple<string, object> temp1;
//表1数据
var Id = Guid.NewGuid().ToString();
sys_Book_Type bty = new sys_Book_Type { };
bty.book_Type_id = Id;
bty.book_Type_Name = Jsons.book_Type_Name;
bty.book_Type_Des = Jsons.book_Type_Des;
bty.create_Time = DateTime.Now;
//表2数据
var Jsonbook = Jsons.books;
List<sys_Borrow_Book> listbooks = new List<sys_Borrow_Book> { };
foreach (var item in Jsonbook)
{
sys_Borrow_Book bk = new sys_Borrow_Book();
bk.book_Id = Guid.NewGuid().ToString();
bk.book_Num = item.book_Name;
bk.book_Name = item.book_Name;
bk.book_Desc = item.book_Desc;
bk.borow_Time = DateTime.Now;
bk.book_Type_id = Id;
bk.user_Id = "ba33a34eb98411e9870700155d08c915";
listbooks.Add(bk);
}
string sql_bookty = "insert into sys_Book_Type(book_Type_id,book_Type_Name,book_Type_Des,create_Time)";
sql_bookty += " values (?book_Type_id,?book_Type_Name,?book_Type_Des,?create_Time)";
temp1 = new Tuple<string, object>(sql_bookty, bty);
para.Add(temp1);
string sql_book = "insert into sys_Borrow_Book(book_Id,book_Num,book_Name,book_Desc,borow_Time,book_Type_id,user_Id)";
sql_book += " values (?book_Id,?book_Num,?book_Name,?book_Desc,?borow_Time,?book_Type_id,?user_Id)";
temp1 = new Tuple<string, object>(sql_book, listbooks);
para.Add(temp1);
bool boolresult = DapperDBContext.ExecuteTransaction(para).Item1;
if (boolresult == true) { result = 1; }
return result;
}
- 在View 文件夹中 创建 Index 视图。
<div class="layui-container">
<div class="layui-col-md12">
<div class="layout">
<fieldset class="layui-elem-field layui-field-title">
<legend>新增</legend>
</fieldset>
<div class="layui-form">
<div class="layui-form-item my-margin"><b>A表</b></div>
<hr class="layui-bg-green">
<div class="layui-form-item" id="bindtitle">
<label class="layui-form-label">书类型名称</label>
<div class="layui-input-block">
<input type="text" name="book_Type_Name" id="book_Type_Name" lay-filter="book_Type_Name" placeholder="请输入标题" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">书类型描述</label>
<div class="layui-input-block">
<textarea class="layui-textarea" name="book_Type_Des" id="book_Type_Des" lay-filter="book_Type_Des" placeholder="请输入书籍类型描述"></textarea>
</div>
</div>
</div>
<div class="laui-form">
<div class="layui-form-item my-margin"><b>B表</b></div>
<hr class="layui-bg-green">
<button class="layui-btn layui-btn-sm" id="btnAddRow">新增</button>
<table class="layui-table" id="tab">
<tr>
<th>借书编号</th>
<th>书名</th>
<th>书简介</th>
<th>操作</th>
</tr>
<tr class="list">
<td><input type="text" name="book_Num" class="layui-input" /></td>
<td><input type="text" name="book_Name" class="layui-input" /></td>
<td><input type="text" name="book_Desc" class="layui-input" /></td>
<td><button class="layui-btn layui-btn-danger layui-btn-sm btnDelRow">删除</button></td>
</tr>
</table>
</div>
</div>
<div class="layui-form-item">
<div style="144px;margin:0 auto;">
<button class="layui-btn layui-btn-normal" id="btnSave">保存</button>
<button class="layui-btn layui-btn-primary" id="btnCancel">取消</button>
</div>
</div>
</div>
</div>
注意:
这里的添加并未对数据进行验证(ps:原谅有点懒的冬瓜~)。- 在index视图中操作dom
<script type="text/javascript">
$(function () {
Del();
/*新增*/
$("#btnAddRow").click(function () {
var str_row = '';
str_row += '<tr class="list">';
str_row += '<td><input type="text" name="book_Num" class="layui-input"/></td>';
str_row += '<td><input type="text" name="book_Name" class="layui-input"/></td>';
str_row += '<td><input type="text" name="book_Desc" class="layui-input"/></td>';
str_row += '<td><button class="layui-btn layui-btn-danger layui-btn-sm btnDelRow">删除</button></td>';
str_row += '</tr>';
$("#tab").append(str_row);
/*删除*/
Del();
});
/*添加*/
$("#btnSave").click(function () {
var bookType = { book_Type_Name: "" + $("#book_Type_Name").val() + "", book_Type_Des: "" + $("#book_Type_Des").val() + "", books: [] };
var tr = $("#tab tr:gt(0)");
for (var i = 0; i < tr.length; i++) {
var td = $(tr[i]);
var aa = td.children().children().val();
var bb = td.children().next().children().val();
var cc = td.children().next().next().children().val();
bookType.books.push({ book_Num: "" + aa + "", book_Name: "" + bb + "", book_Desc: "" + cc + "" });
}
$.ajax({
url: "../BorrowBook/Adds_Op",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(bookType)
}).done(function (msg) {
if (msg==1) {
parent.layer.msg("保存成功!", { icon: 1 });
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
parent.layer.close(index); //再执行关闭
}
else {
parent.layer.msg("保存失败!", { icon: 2 });
return;
}
}).fail(function (e) { });
});
/*取消*/
$("#btnCancel").click(function () {
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
parent.layer.close(index); //再执行关闭
});
});
/*删除*/
function Del() {
$(".btnDelRow").on("click", function () {
$(this).parent().parent().remove();
});
}
</script>
效果图: