如何通过MVC3中的ajax表单发送值?

时间:2012-07-08 20:47:02

标签: asp.net-mvc-3 jquery

我可以上传文件并将其保存到目录中。这一切都很好。我需要使用有关该文件的信息输入我的数据库。到目前为止,我不知道在这种特殊情况下如何将视图中的值传递给控制器​​。我试图将其作为方法参数传递,但该值未发布。

这是我的剃刀形式:

@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以表达形式:

$(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传递给此方法,以便我可以将记录插入数据库。

1 个答案:

答案 0 :(得分:1)

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

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

或作为路线值:

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