I'm new in asp net and I have a List of images and I want to send through javascript to the controller.
I'm using FileList and here is an example. .Create.cshtml
<div class="form-group">
@Html.LabelFor(model => model.description, "Escolha as Imagens", htmlAttributes: new { @class = "control-label col-md-2" })
<input id="files" type="file" name="files[]" />
<br>
<div id="preview"></div>
</div>
@section Scripts{
<script type="text/javascript">
function handleFileSelect(evt) {
var files = evt.target.files;
var f = files[0];
//kiem tra co fai file anh
if (f.type.match('image.*')) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = [
'<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name),
'"/><span class="remove_img_preview"></span>'
].join('');
document.getElementById('preview').insertBefore(span, null);
};
})(f);
reader.readAsDataURL(f);
}
}
$('#files').change(function(evt) {
handleFileSelect(evt);
});
$('#preview').on('click',
'.remove_img_preview',
function() {
$(this).parent('span').remove();
});
$('#btnSave').click(function() {
$.ajax({
url: '/Dishes/Create',
data: { files: files },
type: "POST",
cache: false,
datatype: "html",
success: function(data) {
console.log(data);
},
error: function(jqXhr, textStatus, errorThrown) {
//do your own thing
alert("fail");
}
});
});
</script>
}
</fieldset>
<div class="form-group">
<div class="footer text-center">
<button class="btn btn-fill btn-info" name="btnSave" id="btnSave">Inserir novo</button>
</div>
</div>
Controller.cs
public ActionResult Create()
{
ViewBag.idTypeDish = new SelectList(db.TypeDish, "idTypeDish", "name");
return View();
}
// POST: Dishes/Create
[HttpPost]
public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
{
return View();
}
In the controller, files are always null. I'm using that example, http://jsfiddle.net/Lwczca6p/1/, I just adapt to my project.
multiple="multiple"to your file input (assuming you're using html5 anyway