0

I am using following code to pass file object via JSON to MVC Controller along with data object.

The data object is being catched by MVC Controller method but file always pass as null (JSON object successfully contains file).

Form is not getting submitted. But, calling 'INSETPART' javascript method on save button click. From javascript method,ajax call is initiated.

I want to send html page data along with uploaded file to the controller method.

HTML :

<input name="Image" class="form-control" placeholder="Image" maxlength="50" type="file" accept="image/*" id="txtImage" required="required" />

JSON :

function InsertPart() {
    product = {
        PartName: $("#txtPartName").val(),
        AutoexelPartNo: $("#txtAutoexelPartNo").val(),
        Description: $("#txtDescription").val(),
        Price: $("#txtPrice").val(),
        ImageUrl: $('input[type=file]').val(),
        MakeId: $("#MakeDetails").val(),
        SubCategoryId: $("#SubCategoryDetails").val(),
        PartMasterOEMDetails: OEMDetails,
        PartMasterMappedWithOthers: CrossReferences
    }

    var formData = new FormData();
    var image = $('input[type=file]')[0].files[0];
    var url = '@Url.Action("InsertProduct", "Admin")';

    $.ajax({
        contentType: 'application/json;cjarset=utf-8',
        dataType: 'json',
        type: "POST",
        url: url,
        data: JSON.stringify({ imagefile: image, part: product }),
        async: false,
        success: function (data) {
            $('#divMessage').html(data);
        },

        error: function (response) {
        }
    });
}

MVC Controller:

public ActionResult InsertProduct(HttpPostedFileBase imagefile, PartMaster part)
{
    string Message;
    bool Successful;
    ProductAdminBusiness ba = new ProductAdminBusiness();
    Successful = ba.InsertPartMaster(part);

    if (Successful)
    {
        HttpPostedFileBase myFile = imagefile;
        bool isUploaded = false;
        string message = "";

        if (myFile != null && myFile.ContentLength != 0)
        {
            string pathForSaving = Server.MapPath("~/Content/Store/Products");

            try
            {
                myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
                isUploaded = true;
            }
            catch (Exception ex)
            {
                message = string.Format("File upload failed: {0}", ex.Message);
            }
        }

        Message = "Product added successfully";
    }
    else
    {
     Message = "Unable to add product";
    }

    return Json(Message, MediaTypeNames.Text.Plain);
}
  • The [tag:model-view-controller] is for the discussion of pattern. – Erik Philips Oct 28 '16 at 04:55
  • You need to set the correct ajax options, and you cannot `stringify()` the data or send objects - you need to send just the `FormData` –  Oct 28 '16 at 05:08
  • I am using ajax call and want to send the file and object to Controller Method. Controller Method receives the object data but file as null. – Mukesh Devmurari Oct 28 '16 at 13:15
  • The read and understand the duplicate which shows exactly how to do it –  Oct 30 '16 at 07:13

0 Answers0