【问题标题】:Onclick storing same value multiple timesOnclick 多次存储相同的值
【发布时间】:2016-08-13 05:16:57
【问题描述】:

考虑下面的代码 sn -p

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(MyViewModel viewModel)
{
        if (ModelState.IsValid)
        {
            //map properties here

            using (var context = new MyEntities())
            {
                context.Users.Add(user);
                context.SaveChanges();
            }

            if (Request.Files.Count > 0)
            {
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];
                    if (file != null && file.ContentLength > 0)
                    {
                       //do checks and upload file here
                    }
                }
            }
        }
        return RedirectToAction("Index", "Home");
}

表单可以单独提交,也可以与文件一起提交,然后上传到服务器。现在我的问题是,如果我提交的表单没有任何文件或只有一个文件,那么一切都会按预期工作。但是,用户一次可以上传多个文件,这就是问题所在。文件被上传,但我在数据库中获得了该特定表单的多个条目。例如,如果用户上传三个文件,我将在数据库中得到三个完全相同的条目。

所以我的问题是如何解决这个问题?

在客户端,我使用DropZoneJs 并将方法调用为

<script>
    Dropzone.autoDiscover = false;
    var myDropZone = new Dropzone("#dzUpload", {
        url: "/Home/Create",
        autoProcessQueue: false,
        previewsContainer: ".preview",
    });

    $("#submit-all").attr("type", "button").on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        if (myDropZone.getQueuedFiles().length > 0) {
            myDropZone.options.autoProcessQueue = true;
            myDropZone.processQueue();
        }
        else {
            $("#dzUpload").submit();
        }
    });
</script>

我也遇到过 this 问题,但我仍然遇到同样的问题

【问题讨论】:

    标签: c# asp.net-mvc dropzone.js


    【解决方案1】:

    看起来uploadMultiple 选项会改变行为,因此只有一个请求会发送到服务器。

    var myDropZone = new Dropzone("#dzUpload", {
        url: "/Home/Create",
        autoProcessQueue: false,
        previewsContainer: ".preview",
        uploadMultiple: true,
    });
    

    【讨论】:

    • 这正是我使用的,问题已解决
    【解决方案2】:

    如果我是对的,插件会为您放入插件的每个文件发布表单,对吗?一种方法是生成一个 GUID 并在表单隐藏输入中维护它。因此,每次您的插件发布时,它也会发布此 GUID。因此,将您的插入语句更改为基于 Guid 的 upsert(更新或插入)。您必须将此 GUID 与其他数据一起保存。

    因此,每次您打算插入时,请检查 GUID 是否已经存在,如果存在则更新它,否则插入新记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 2022-10-26
      • 2012-04-22
      相关资源
      最近更新 更多