【问题标题】:Upload file with .net core MVC using ajax and pass as model使用 ajax 使用 .net core MVC 上传文件并作为模型传递
【发布时间】:2018-06-23 20:19:00
【问题描述】:

我正在尝试使用带有 mvc ajax 的 .net 核心上传图片

这是我的代码

<form asp-action="AddImages" asp-controller="UserAdmin"
                      data-ajax-begin="onBeginSubmit" data-ajax-complete="onComplete"
                      data-ajax-failure="onFailed" data-ajax-success="onSuccessSubmit"
                      data-ajax="true" data-ajax-method="POST" enctype="multipart/form-data">
                                <input id="file-input-1" name="Image" type="file" class="uploadimg" data-id="1" accept=".jpg, .jpeg, .png" />

                    <div class="col-xs-12">
                        <button type="submit">Save</button>
                    </div>
                </form>

这是我的模型

public class ImageModel
    {
        [Required(ErrorMessage = "Please Select Image of Product")]
        public List<IFormFile> Image { get; set; }
    }

还有我的方法

  [HttpPost]
        public bool AddImages(ImageModel Image)
        {
            if (!ModelState.IsValid)
            {
                return false;
            }
            return true;
        }

Image 为 null 且模型始终返回 false

【问题讨论】:

  • 在您的模型中,您有 IFormFile 列表,并且您正在传递 IFormFile 的单个值。将 Image 的数据类型从 List 更改为 IFormFile 或第二个选项将 html 中的输入名称从 Image 更改为 Image[0]。
  • 看来你的代码没有问题。应该还有一些你没有与我们分享的东西。
  • 我试过不使用 ajax 它的工作 "
    "跨度>
  • ajax 可能有什么问题?

标签: c# ajax file .net-core asp.net-core-mvc


【解决方案1】:

我自己刚刚遇到了这个问题,似乎唯一的解决方法是使用“传统”ajax 将表单发布回控制器。我的方法如下:-

将提交按钮替换为调用 Ajax 的普通按钮:

<input type="button" class="btn btn-default" value="Save" onclick="javascript:submitForm()" />

然后使用 Ajax 收集表单数据并将其发送回控制器操作:

 function submitForm() {
    var formdata = new FormData($('#yourFormId').get(0));
    $.ajax({
        url: '@Url.Action("YourActionName", "YourControllerName")',
        type: 'POST',
        data: formdata,
        processData: false,
        contentType: false,
        success: function (data) {
            //rendering success
        },
        error: function (xhr, ajaxOptions, thrownError) {
            //rendering errors
        }
    });
}

希望这可以帮助某人。可惜新的“data-ajax”表单标签似乎无法处理回发文件。

【讨论】:

    猜你喜欢
    • 2013-07-27
    • 2019-08-06
    • 2011-01-20
    • 2019-11-28
    • 2013-12-23
    • 2012-11-27
    • 2015-10-28
    • 2019-10-21
    • 2020-11-22
    相关资源
    最近更新 更多