我是ajax和.net MVC的新手。
我的应用程序中有mvc表单助手的形式,并尝试使用其他表单字段上传文件。
@using (Html.BeginForm("upload", "upload", FormMethod.Post, new { enctype = "mutipart/form-data" })) {
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.cardTitle)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.cardTitle, new { @Class = "span12", type = "text" })
</div>
<div class="editor-label">
@Html.LabelFor(model => model.cardHashCode)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.cardHashCode, new { id = "cardhashcode" })
</div>
<input type="file" name="file" id="file_upload" />
<input type="submit" class="btn btn-success" value="Create One" />
</fieldset>
}
控制器 -
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, CardModel card, FormCollection forms) {
CardTable cardtable = new CardTable();
if (file != null && file.ContentLength > 0) {
// TODO: storing uploaded files to the App_Data folder on the server.
// Adjust this location to fit your requirements
var filepath = "D:\\FunRanger2\\FunRangerPhotos";
var filename = Path.Combine(filepath, Path.GetFileName(file.FileName));
file.SaveAs(filename);
cardtable.CardFileName = file.FileName;
cardtable.CardFilePath = filepath;
cardtable.CardDate = DateTime.Now;
cardtable.CardTitle = card.cardTitle;
cardtable.CardHashCode = card.cardHashCode == null ? "" : card.cardHashCode;
db.CardTables.InsertOnSubmit(cardtable);
db.SubmitChanges();
}
}
我只在输入字段的模型中获取值,文件始终为null。
我尝试通过脚本映射它 -
通过为表单#form-upload
和按钮button-upload
<script type="text/javascript">
$(function(){
$('#button-upload').click(function(){
$.ajax({
url:'/Upload/Upload/',
data:$('#form-upload').serialize()+$('#file_upload').file,
success:function(){
alert("Uploaded successfully");
}
});
});
});
</script>
如何使用其他表单字段上传文件?请帮帮我!
答案 0 :(得分:-1)
以这种方式使用,我来自不同网站的搜索。
// Get form
var form = $('#fromEdit')[0]; // Important!
// Create an FormData object
var data = new FormData(form); // Important!
alert(form);
alert(data);
$.ajax({
type: "POST",
enctype: 'multipart/form-data', // Important!
url: $(this).attr('action'), // Important!
data: data,
processData: false, // Important!
contentType: false, // Important!
cache: false,
success: function(res) {
alert("Records added Successfully.");
}
});
public ActionResult Create([Bind(Exclude = "FileContent")] ProductEntity productEntity) {
foreach(string file in Request.Files) {
HttpPostedFileBase postedFile = Request.Files[file];
}
}