如何将图像文件和表单数据从Ajax传递到MVC控制器 [英] How to Pass Image File and Form Data From Ajax to MVC Controller
本文介绍了如何将图像文件和表单数据从Ajax传递到MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含Image和另一个文件的表单,我想在控制器中发送包含image的数据.
I have a form with Image and another fileds, I want to send data with image in controller.
<form id="first-form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-9">
<div class="row">
<div class="col-sm-6 form-group">
@Html.Label(@RegisterResource.Name, new { @class = "control-label" })
<div class="field-input">
@Html.TextBox("Name", null, new { placeholder = @RegisterResource.Name, autofocus = "autofocus", @class = "input-text" })
@Html.ValidationMessage("Name", null, new { @class = "text-danger" })
</div>
</div>
<div class="col-sm-6 form-group">
@Html.Label(@RegisterResource.Family, new { @class = "control-label" })
<div class="field-input">
@Html.TextBox("Family", null, new { placeholder = @RegisterResource.Family, @class = "input-text" })
@Html.ValidationMessage("Family", null, new { @class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
@Html.Label(@RegisterResource.CellPhone, new { @class = "control-label" })
<div class="field-input">
@Html.TextBox("CellPhone", null, new { placeholder = @RegisterResource.CellPhone, maxlength = 11, @class = "input-text", onkeydown = "return ValidateNumber(event);" })
@Html.ValidationMessage("CellPhone", null, new { @class = "text-danger" })
</div>
</div>
<div class="col-sm-6 form-group">
@Html.Label(@ContractorResource.City, new { @class = "control-label" })
<div class="field-input">
@Html.DropDownList("CityId", (SelectList)ViewBag.City, new { placeholder = @ContractorResource.City, @class = "input-text" })
@Html.ValidationMessage("CityId", null, new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="col-md-3 text-center">
<img id="image_upload_preview" class="img-circle" src="~/Content/Images/contractor-avator.png" />
<br />
<input type="file" id="inputFile" style="max-width: 200px" />
<label for="inputFile" class="btn-2">انتخاب فایل تصویر</label>
</div>
</div>
<div class="order-complate text-center">
<button type="submit" class="awe-btn awe-btn-1 awe-btn-medium" id="user-register-btn" data-loading-text="<i class='fa fa-spinner fa-spin '></i> @PageResource.ConfirmCode">@PageResource.Continues</button>
</div>
</form>
和在jQuery中
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#image_upload_preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
fileImage = input.files[0];
}
}
$("#inputFile").change(function() {
readURL(this);
});
submitHandler: function() {
$("#user-register-btn").button('loading');
var data = $('#first-form').serialize();
var formData = new FormData();
formdata.append("img", fileImage );
$.post("/Contractor/SendConfirmCode",
data,
function(result) {
}
else {
}
},
"json");
但是在控制器中,Request.Files
是Empty
.
推荐答案
感谢 @jishan 的全面回答;
如果我是您,我希望使用视图模型来发布表单数据,
If I were you, I would prefer a view model for posting the form data, however,
根据您的视图:
$('#user-register-btn').click(function (e) {
e.preventDefault();
$("#user-register-btn").button('loading');
//var data = $('#first-form').serialize();
var data = {
Name: $('#Name').val(),
Family: $('#Family').val(),
CityId: $('#CityId').val(),
CellPhone: $('#CellPhone').val()
};
var formData = new FormData();
formData.append("data", JSON.stringify(data));
var totalFiles = document.getElementById('inputFile').files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById('inputFile').files[i];
formData.append("httpPostedFileBase", file);
}
$.ajax({
type: "POST",
// same as @jishan's answer
});
});
和在您的控制器中:
[HttpPost]
public ActionResult SendConfirmCode(HttpPostedFileBase[] httpPostedFileBase, string data)
{
if(Request.Files.Count > 0)
{
// as you wish
}
ModelForm formData = JsonConvert.DeserializeObject<ModelForm>(data);
// save formData to DB or ...
return View();
}
,以及与表单数据匹配的模型类:
and, the model class that matches the form data :
public class ModelForm
{
public string Name { get; set; }
public string Family { get; set; }
public string CityId { get; set; }
public string CellPhone { get; set; }
}
这篇关于如何将图像文件和表单数据从Ajax传递到MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文