2

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.

3
  • 1
    You probably don't need to do all of that, but if you're going to allow multiple files to be uploaded, then you'll want to add multiple="multiple" to your file input (assuming you're using html5 anyway Commented Jun 6, 2017 at 13:38
  • 1
    @Ortund Ya I know what you mean, but If he selects 2 images, then he goes select another one, what happens? I have a FileList, I can't send the FileList to the controller? Commented Jun 6, 2017 at 13:49
  • @Ortund I'm using all that code, because, before uploading to the server, the user can preview the image and deleted if he wants. Commented Jun 6, 2017 at 13:56

2 Answers 2

2

You've got a few problems. First, you're trying to use files with your AJAX, but that variable was defined in the scope of another function (i.e. you don't have access to it here). Second, when using jQuery's $.ajax to do a file upload, you need to set the processData option to false. Here's how I would handle it:

$('#MyForm').on('submit', function (e) {
    e.preventDefault();
    var formData = new FormData(this); // `this` is the form instance
    $.ajax({
        url: '/path/to/handler',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: 'multipart/form-data',
        success: function (data, textStatus, jqXHR) {
            // do something on success
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // do something on error
        }
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

hey, thanks for your answer, but how would it work on the controller? What parameters would I have instead? I never used FormData before.
1

Try this, first create a model for your view:

public class FileModel  
{  
    [Required(ErrorMessage ="Please select file.")]  
    [Display(Name ="Browse File")]  
    public HttpPostedFileBase[] files { get; set; }  

}  

Then, edit your view to this (to enable upload many files you need to put multiple="multiple" in your element):

@model Models.FileModel

@using (Html.BeginForm("Create", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" }))  
{  
    @Html.AntiForgeryToken()  

    <div class="form-horizontal">  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" })  
                @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit"  value="Upload" class="btn btn-primary" />  
            </div>  
        </div>  

        </div>  
}  

4 Comments

Well, thanks for your answer! But thats not really what I want...I want to be able to select an image one by one, and in the end send the array of files to the controller.
ohh ok. Have you tried to use Dropzone? dropzonejs.com I used it once with asp.net mvc. If you want, I can send you an example.
No, I never used dropzone, but from what I read it instantly uploads to the server, and that's not what I want... I want to be able to add and delete images and then upload when the product is registered. But yes I would like an example if you don't mind.
I wrote this post in my blog about dropzone, I hope it helps. tiagoavilablog.com/utilizando-dropzonejs-com-asp-net-mvc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.