使用asp.net mvc 过程中 参数传递的问题记录。

环境:asp.net MVC

需求:要实现主从表数据存储,主表为结构化信息,附表为对应的图片。

实现过程: 页面中当用户在新建数据的时候,未保存时没有主表的主键,同时用户也会选择要上传的图片一同保存。 

使用 ajaxfileupload.js 实现多文件上传,上传之后 通过window.URL.createObjectURL 将上传的文件 转换成BlobURL,创建动态img标签用于预览,

 $('#uploadFile').change(function (e) {
            var f = document.getElementById('uploadFile').files;

            for (var i = 0 ; i < f.length; i++) {
                selectedFiles.push(f[i]);
                var li = document.createElement("li");
                var src = window.URL.createObjectURL(f[i]);
                var img = document.createElement('img');
                img.src = src;
                img.width = 245;
                (function (index) {
                    $(img).bind("dblclick", function () {
                        var index = Array.from(this.parentNode.children).indexOf(this);
                        selectedFiles.splice(index, 1); // 从数组中移除文件
                        $(this).remove();
                    })
                })(selectedFiles.length - 1);
                li.appendChild(img);
                document.getElementById("imglist").appendChild(li);
            }
            e.target.value = '';
    });

 

考虑用户在使用过程中,可以进行多次选择,出现了input[file] 的change事件只出发一次,导致不能选择图片之后立即显示,所以 在函授的的最后 通过清空 input[file]的value 来保证每次都能触发。

同时增加了图片双击删除的功能。

1  (function (index) {
2                     $(img).bind("dblclick", function () {
3                         var index = Array.from(this.parentNode.children).indexOf(this);
4                         selectedFiles.splice(index, 1); // 从数组中移除文件
5                         $(this).remove();
6                     })
7                 })(selectedFiles.length - 1);

 

因为使用了框架,框架中在提交表单后自动刷新,所以在提交表单后在进行文件上传的方式不可行。

偷懒后,先上传文件,返回上传文件的虚拟路径,然后在进行主表数据的保存。但是在保存过程中发现了 Controller 中无法接收到 要传过来的参数,过程不赘述了上结果

controller的函数

    [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [ValidateInput(false)]
        public ActionResult SaveForm(string keyValue, HousesInfoEntity entity,string ImgEntityJson)
        {
            string houseid = housesinfobll.SaveForm(keyValue, entity);
            List<ResourceTableEntity> ImgEntryList = ImgEntityJson.ToList<ResourceTableEntity>();
            return Success("操作成功。",houseid);
        }

其中

HousesInfoEntity 为对象实体
ImgEntityJson   为上传的图片成功后的路径集合

前台代码
var postData ={省略属性}; // postData中的属性 与
HousesInfoEntity 完全对应
postData["ImgEntityJson"] = [{省略}]

这样在Action中即可接受到对应的参数了。
 


 

posted @ 2024-10-30 14:54  雷鸣_Sky  阅读(9)  评论(0)    收藏  举报