0
我有能力上傳文件並將其保存到目錄。這很好。我需要在數據庫中輸入關於該文件的信息。到目前爲止,我不知道如何在這個特殊情況下將視圖中的值傳遞給控制器。我曾嘗試將它作爲方法參數傳遞,但該值未發佈。如何通過MVC3中的ajax表單傳遞值?
這裏是我的剃刀形式:
@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傳遞給此方法,以便我可以將記錄插入到數據庫中。
這偉大工程!我使用了路由值。我不知道爲什麼我沒有想到這一點!感謝您的快速回復。 – Ryan 2012-07-08 20:54:29