我試圖上傳圖像時遇到此問題。當我點擊提交按鈕,我得到以下錯誤:clickASP MVC中的圖像上傳錯誤
當我使用withaut模式PARAM它的工作原理,但窗口不模式,並期待非常糟糕。
型號:
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" })){
@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" })
}
創建視圖:
@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發佈時,表單編碼類型是否會丟失? –
對不起,我是begginer,我不知道你是什麼意思 – Ebasse
我的意思是你添加enctype multipart/form-data到表單,但是你通過一個ajax文章提交你的文件,而我沒有看到攜帶相同編碼類型。 –