Ryan
Ryan

Reputation: 672

How would I pass a value via a ajax form post in MVC3?

I have the ability to upload a file and save it to a directory. That is all good. I need to make an entry to my database with information about that file. So far I am not sure how to pass a value from the view to the controller in this particular case. I have tried to pass it as a method parameter but the value is not getting posted.

Here is my Razor form:

@using (Html.BeginForm("AjaxUpload", "Cases", FormMethod.Post, new { enctype = "multipart/form-data", id = "ajaxUploadForm" }))
        {
        <fieldset>
        <legend>Upload a file</legend>
        <label>File to Upload: <input type="file" name="file" />(100MB max size)</label>

        <input id="ajaxUploadButton" type="submit" value="Submit" />

        </fieldset>
        }
    <div id="attachments">
        @Html.Partial("_AttachmentList", Model.Attachments)
    </div>

Here is my jQuery to ajaxify the form:

$(function () {
    $('#ajaxUploadForm').ajaxForm({
        iframe: true,
        dataType: "json",
        beforeSubmit: function () {
            $('#ajaxUploadForm').block({ message: '<h1><img src="/Content/images/busy.gif" /> Uploading file...</h1>' });
        },
        success: function (result) {
            $('#ajaxUploadForm').unblock();
            $('#ajaxUploadForm').resetForm();
            $.growlUI(null, result.message);
            //$('#attachments').html(result);
        },
        error: function (xhr, textStatus, errorThrown) {
            $('#ajaxUploadForm').unblock();
            $('#ajaxUploadForm').resetForm();
            $.growlUI(null, 'Error uploading file');
        }
    });

});

Here is the controller method:

public FileUpload AjaxUpload(HttpPostedFileBase file, int cid)
        {
        file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));

        var attach = new Attachment { CasesID = cid, FileName = file.FileName, FileType = file.ContentType, FilePath = "Demo", AttachmentDate = DateTime.Now, Description = "test" };
        db.Attachments.Add(attach);
        db.SaveChanges();

        //TODO change this to return a partial view
        return new FileUpload { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
        }

I would like cid to be passed to this method so that I can insert a record into the database.

Upvotes: 0

Views: 1114

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You could include it as a hidden field inside the form:

@Html.Hidden("cid", "123")

or as a route value:

@using (Html.BeginForm(
    "AjaxUpload", 
    "Cases", 
    new { cid = 123 },
    FormMethod.Post, 
    new { enctype = "multipart/form-data", id = "ajaxUploadForm" }
))
{
    ...
}

Upvotes: 1

Related Questions