dotnetdev_2009
dotnetdev_2009

Reputation: 791

Single file upload using Ajax, MVC 5 and jQuery

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?)

Upvotes: 0

Views: 2464

Answers (1)

Ricky
Ricky

Reputation: 498

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"/>

Upvotes: 1

Related Questions