0

I am using asp.net MVC 5 to do a simple single file upload using the HTML element.I make an AJAX post request.The form has other fileds in addition to the file element.I tried diffrent methods available on the internet ,but nothing seems to be working.Is this really possible using the element?Using a jQuery plugin is my last option.I like to make things simple in my application

my HTML

@using (Html.BeginForm("Edit", "Person", FormMethod.Post, new {  id = "form-person-edit-modal",  enctype = "multipart/form-data" }))
{    
    <div class="row">        
        <div class="row">
            <div class="small-4 columns">
                @Html.GenericInputFor(m => m.Name, Helpers.HtmlInputType.Text, new { id = "input-name" })
            </div>   

            <div class="small-4 columns">
                @Html.GenericInputFor(m => m.Description, Helpers.HtmlInputType.TextArea, new { id = "input-description" })
            </div>  
            <div class="small-4 columns">   
            <label>Choose File</label>
            <input type="file" name="attachment" id="attachment" />
            </div>          
        </div>       
    </div>
    <div class="row">
        <div class="small-12 columns">
            <input type="submit" id="image-submit" value="Save"/>
        </div>
    </div>
}

-- C# ViewModel

 public class Person
 {
    Public string Name{get;set;}
    Public string Description{get;set;}
    public HttpPostedFileBase Attachment { get; set; }

 }

-- Jquery Ajax Post:

$.ajax({
        url: url,
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            if (data.Success) {
                success(data, textStatus, jqXHR);
            } else {                
                if (error) {
                    error();
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {            
            if (error)
                error();
        }

    });

-- Javacsript where I try to get the file content,before passing that data to the above method

function getData(){
       return {
          Name:$('#input-name').val(),
          Description:$('#input-description').val(),
          Attachment:$('#form-ticket-edit-modal').get(0).files[0]
       };
    }

But the Attachment on the controller is null.I tried this as below,but doesnt seem to be working

[HttpPost]
 public ActionResult Edit(ViewPerson person,HttpPostedFileBase attachment)
 {

 }

Is this still possible,or should I use a jQuery plugin(If so,which one do you recommend?)

4
  • 1
    This will work fine using a standard submit. If your using ajax, then your need to use FormData (HTML5) Refer Sending files using a FormData object Commented Nov 18, 2014 at 2:38
  • Thanks man.I changed the javacsript function from Attachment:$('#form-ticket-edit-modal').get(0).files[0] to Attachment: getFileData() and getFileData:function(){ var data = new FormData(); data.append('attachment', $('#attachment').get(0).files[0]); return data; } and was bale to see the Attachment as part of the viewmodel.But the only issue that I see is this only works with IE10 and later Commented Nov 18, 2014 at 2:57
  • 1
    Yes unfortunately FormData is only supported in modern browsers. I have seen ways this can be done without FormData but can't find the link. If I come across it I add a new comment. Commented Nov 18, 2014 at 4:27
  • Does anybody know whether I can do an Ajax single file upload with other form fields on the UI in a single HTTP POST request to the Asp.Net MVC controller? Commented Nov 21, 2014 at 20:10

1 Answer 1

1

I have used your code to show how to append image file,Please use Formdata() method to append your data and File and send through ajax. Try Changing as per your requirement.

$("#SubmitButtonID").on("click",function(){
var mydata=new Formdata();
mydata.append("Name",$("#name").val());
mydata.append("Image",Image.files[0]);
alert(mydata);
$.ajax({
        url: "@url.Action("ActionMethodName","ControllerName")",
        type: 'POST',
        contentType:false,
        processData;false,
        data: mydata,
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            if (data.Success) {
                success(data, textStatus, jqXHR);
            } else {                
                if (error) {
                    error();
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {            
            if (error)
                error();
        }

    });
    });
    <input type="file" id="Image" name="file">
    <input type="button" id="SubmitButtonID" value="submit"/>

Sign up to request clarification or add additional context in comments.

1 Comment

FormData is correct; don't spend 20 minutes wondering what's wrong like I just did.

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.