【发布时间】:2016-08-03 12:35:12
【问题描述】:
我在尝试上传图片时遇到了这个问题。当我点击提交按钮时,我收到以下错误:
索引代码:
当我在没有模态参数的情况下使用它时,它可以工作,但窗口不是模态的,看起来很糟糕。
型号:
public partial class Prod
{
public string PName { get; set; }
public byte[] PFile{ get; set; }
}
索引视图:
@using (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
@Html.ActionLink(" ", "Create", "Products", null, new { data_modal = "file", id = "btnCreate", @class = "btn btn-small btn-primary pull-right fa fa-cart-plus" })
@Html.ActionLink(" ", "Create", "Products", null, new { id = "btnCreate", @class = "btn btn-small btn-primary pull-right fa fa-cart-plus" })
</p>
}
创建视图:
@using (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.PFile, "Plik", htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-9">
@Html.TextBoxFor(model => model.PFile, new { type = "file", name = "imageF" })
@Html.ValidationMessageFor(model => model.PFile, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Anuluj</button>
<input class="btn btn-primary" type="submit" value="Zapisz" />
</div>
}
控制器:
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = "PFile")] Prod pro, HttpPostedFileBase imageF)
{
if (ModelState.IsValid)
{
if (imageF != null)
{
pro.PName= imageF.ContentType;
pro.PFile= new byte[imageF.ContentLength];
imageF.InputStream.Read(pro.PFile, 0, imageF.ContentLength);
}
db.Prods.Add(pro);
db.SaveChanges();
return Json(new { success = true });
}
return PartialView("Create", pro);
}
modalform.js
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
// hide dropdown if any
$(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
/*backdrop: 'static',*/
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
contentType: 'multipart/form-data',
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
//Refresh
location.reload();
} else {
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
有什么问题?请帮忙解决这个问题。
【问题讨论】:
-
通过ajax发帖是不是表单编码类型丢失了?
-
对不起,我是初学者,我不知道你是什么意思
-
我的意思是您在表单中添加了 enctype multipart/form-data,但随后您通过 ajax 帖子提交文件,而我没有看到它带有相同的编码类型。
-
我在我的 JS 文件中添加了:contentType:'multipart/form-data',但没有帮助(请看 - 我编辑了代码)。也许我做错了什么
标签: asp.net asp.net-mvc base64 image-upload