我正在尝试使用 .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/