How to receive a form with file and form in controller ? C #

Asked

Viewed 400 times

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);
            }
        },
    });
}
  • 1

    Is missing open the { in the second function.

1 answer

2


Good is very simple, just put the two in the same method:

public JsonResult Import(FormCollection form, HttpPostedFileBase file)

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

Observing: the name of the guy FormCollection can be any name, already the HttpPostedFileBase must be the same name as input who’s kind file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.