通过Ajax将数据和文件上传到控制器而不返回Ajax?

时间:2015-08-26 22:12:26

标签: c# ajax asp.net-mvc file-upload

我有一个MVC表单,其中包含文本数据和文件。当我提交表单时,预期的结果是文件被上传,一旦成功,将出现一个模态并显示从控制器返回的值。但是,实际发生的是文件被上传,但控制器永远不会将值返回给ajax函数。相反,文本在新的空页面上显示给浏览器(url路径指向控制器)。 正在使用的ajax调用基于以下帖子:Uploading both data and files in one form using Ajax?

但是,如果ajax调用使用data: $(form).serialize(),则ajax调用将返回所需的值并显示模态。但是,该文件不包含在ajax调用中。

我非常感谢有关需要更改的建议,以便表单正常运行,以便:

a)文件可以上传,

b)返回ajax函数的值

提前致谢。

形式:

@using (Html.BeginForm("Submit", "QuoteRequest", FormMethod.Post, new { id = "contactForm", enctype = "multipart/form-data" }))
{   
    @Html.LabelFor(x => x.FirstName)                       
    @Html.TextBoxFor(x => x.FirstName, new { placeholder = "Your First Name" })
    @Html.ValidationMessageFor(x => x.FirstName)          
    <input type="file" id="Artwork" class="button" name="Artwork" value="Choose File" />                       
    <input type="submit" class="button" value="Submit" />
}

的Ajax:

$('#contactForm').submit(function (ev) {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this)[0].serialize(),
        success: function (result) {                        
           $('#divMsg h2').html('Thank you for contacting us.');
           $('#hdnResponseVal').val("Success");
        },
        fail: function (result) {
           alert("fail");
        }
    });
    ev.preventDefault();
});

控制器:

[HttpPost]
public ActionResult Submit(QuoteRequestModel model)
{           
    string retValue = "There was a problem submitting your request. Please try again later.";
    if (!ModelState.IsValid)
        return Content(mretValue);

    try
    {
        string folderName = model.CompanyName;
        string filename = "";
        var contentService = Services.ContentService;
        var mediaService = Services.MediaService;
        int folderId = 0; ;

        if (model.Artwork != null)
        {
            //process the file
        }
        retValue = "We'll be in touch shortly.";
    }
    catch(Exception e)
    {
        retValue = "There was a problem submitting your request. Please try again later.";
    }
    return Content(retValue);        
}

0 个答案:

没有答案