asp.net mvc添加多条数据到数据库

来源:互联网 发布:arma3服务器端口 编辑:程序博客网 时间:2024/04/29 19:59

转自:http://www.cnblogs.com/jetjing/p/4275014.html

mvc的视图太强大了,个人刚刚接触。(初级菜鸟,懂的不多,往大神们指点)需求是,客户点击添加按钮弹出一个框选择产品后直接添加到表单中,在表单可以自己更改产品的数量,以及一些信息。mvc表单提交的时候只要name属性和要提交的控制器里面方法的参数一样mvc就能自动识别,利用这个好处就可以很轻松的提交多条数据。

如图显示

前台代码(没有用mvc的一些扩展方法,@Html 之类的,我是为了说明添加多个表单)

复制代码
<form action="/Home/Add" method="post">    <table id="tb">        <tr>            <th>商品名称</th><th>商品数量</th><th>商品类型</th>        </tr>        @for (int i = 1; i < 10; i++)        {            <tr>                <td><input type="text" name="ProductName" value="名称                @i                " /></td>                <td><input type="text" name="ProductNum" value="数量                @(i+3)                " /></td>                <td><input type="text" name="ProductType" value="类型了" /></td>            </tr>        }            </table>    <br />    <input type="submit" id="" value="提交" /></form>
复制代码

后台代码

复制代码
 public ActionResult Index()        {            return View();        }        [HttpPost]        public ActionResult Add(List<string> ProductName, List<string> ProductNum, List<string> ProductType)        {            for (int i = 0; i < ProductName.Count; i++)            {                Product mod = new Product();                mod.ProductName = ProductName[i];                mod.ProductNum = ProductNum[i];                mod.ProductType = ProductType[i];                ProductSubmit(mod);            }            return View();        }        public bool ProductSubmit(Product mod)        {            //这里就可以直接执行EF 添加数据发方法了            //  db.Add(mod);             return true;        }
复制代码

 

首先打开当我们提交表单的时候,用谷歌自带插件看到把他这些数据提交了

 

到后台第一次逐个的遍历每条数据,因为传来的数据name有很多相同的,所以选择用多个集合参数接受 用数组也可以,定义一个类专门接受应该也可以的

每循环一次得到一组数据,添加到数据中去,最后直接用  db.add(mod) ,然后保存就OK了

 


0 0
原创粉丝点击