How to receive a formData with file and form in the controller? W #

1

So I get the form:

public JsonResult Import(**FormCollection** form)

So I get the file:

public JsonResult Import(**HttpPostedFileBase** file)

    $.ajax({
        url: urlImport,
        method: 'post',
        data: new FormData($('#formUpdate')[0],
        cache: false,
        contentType: false,
        processData: false,
        success: function (result) {
            if (result.Success === true) {
                ShowMessageSuccess('Process', result.MsgReturn);
            } else {
                ShowMessageError('Process', result.MsgReturn);
            }
        },
    });
}
    
asked by anonymous 22.08.2018 / 15:28

1 answer

2

Well it's very simple, just put the two in the same method:

public JsonResult Import(FormCollection form, HttpPostedFileBase file)

Minimum example:

HTML

<form name="formUpdate" id="formUpdate">
    <input type="text" id="nome" name="nome" />
    <input type="file" id="file" name="file" />
    <button type="button" onclick="send();">Enviar</button>
</form>

<script>
    function send() {
        $.ajax({
            url: '/home/save',
            method: 'post',
            data: new FormData($('#formUpdate')[0]),
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                console.log(result);
            }
        });
    }
</script>

Controller

[HttpPost]
public ActionResult Save(FormCollection form, HttpPostedFileBase file)
{
    return Json(new { });
}

Note: The type name FormCollection can be any name, since HttpPostedFileBase must be the same name as input which is of type file .

    
22.08.2018 / 15:57