c# - 使用ajax使用.net core MVC上传文件并作为模型传递

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

我正在尝试使用 .net core 和 mvc ajax 上传图像

这是我的代码

<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;
        }

但是图像为空并且模型始终返回 false

最佳答案

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

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

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

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

 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”表单标签似乎无法处理回传文件。

关于c# - 使用ajax使用.net core MVC上传文件并作为模型传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48258967/

相关文章:

asp.net - AjaxPro 无法在 .Net Framework 4.0 和 Server 2008/IIS 7 上运行

javascript - 脚本谜题 &lt;script src ="ajaxpage.php?emp_id=23"/>?

c - 使用结构写入文件

c# - DataContext ="{Binding}"是什么意思?

c# - CaSTLe DynamicProxy - 创建涉及用作 GTR 的 GTP 的代理时失败

c# - ASP.NET MVC : How to reliably get the real URL of the current request?

java - 拆分字符串类型并放入循环中的新数组中

c# - Winforms中OleDb参数查询(C#) : no errors but no rows updated

javascript - 停止从 javascript ajax 请求提交

file - 如何为 MP4 文件创建缩略图系统