无法通过JSON将html5文件与数据对象一起传递给Controller

时间:2016-10-28 04:53:15

标签: c# json asp.net-mvc html5

我使用以下代码通过JSON将文件对象与数据对象一起传递给MVC控制器。

MVC Controller方法正在捕获数据对象,但文件始终作为null传递(JSON对象成功包含文件)。

表单未提交。但是,打电话给'INSETPART'点击保存按钮的javascript方法。从javascript方法开始,启动ajax调用。

我想将html页面数据和上传的文件一起发送到控制器方法。

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控制器:

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);
}

0 个答案:

没有答案