0

我能够上传文件并将其保存到目录中。这都很好。我需要在我的数据库中输入有关该文件的信息。到目前为止,我不确定在这种特殊情况下如何将值从视图传递给控制器​​。我试图将它作为方法参数传递,但没有发布该值。

这是我的剃刀形式:

@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>

这是我的 jQuery 来 ajaxify 表单:

$(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');
        }
    });

});

这是控制器方法:

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

我希望将 cid 传递给此方法,以便我可以将记录插入数据库。

4

1 回答 1

1

您可以将其作为隐藏字段包含在表单中:

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

或作为路由值:

@using (Html.BeginForm(
    "AjaxUpload", 
    "Cases", 
    new { cid = 123 },
    FormMethod.Post, 
    new { enctype = "multipart/form-data", id = "ajaxUploadForm" }
))
{
    ...
}
于 2012-07-08T20:49:37.497 回答