[英]How to upload image with all entered textbox value using AJAX in asp.net MVC 5 without Form or Beging form tag?
我不想重新加載我的頁面所以我使用AJAX,這里的Index.cshtml頁面用於文本框上傳圖像。 此代碼目前正在運行,但我想使用ajax將數據從cshtml頁面傳遞到控制器端,而不使用表單標記。
<form class="form-horizontal" id="fc" action="@Url.Action("SaveAcademy", "Academy")" method="post" enctype="multipart/form-data">
@Html.AntiForgeryToken()
<input type="text" class="form-control" onblur="checktxtvalidation(this.id)" name="txtacademyname" id="txtacademyname">
<input type="file" class="form-control" name="fileupload" id="fileupload" multiple="multiple">
<input type="submit" value="submit" id="submit" name="submit" class="btn btn-block btn-primary" />
</form>
調節器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveAcademy(HttpPostedFileBase fileupload, FormCollection fc)
{
....
.... here are some code for inserting data into database
....
}
<input type="file" class="form-control" name="fileupload" id="fileupload" >
它不需要在表單標簽中。
<script type="text/javascript">
$('#fileupload').on('change', function (e) {
var files = e.target.files;
var text=$('#txtacademyname').val();
if (files.length > 0) {
var data = new FormData();
data.append("file", files[0]);
data.append("acatext", text);
console.log(data);
$.ajax({
type: "POST",
url: '@Url.Action("SaveAcademy","Academy")',
contentType: false,
processData: false,
data: data,
success: function (data) {
alert(data);
},
error: function () {
}
});
}
});
您可以使用按鈕來觸發上傳或像我的演示只使用更改事件。如果您不添加processData: false
以防止自動處理,您將收到'Illegal Invocation'
。
[HttpPost]
public ActionResult SaveAcademy(HttpPostedFileBase file, string acatext)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var location = Path.Combine(
Server.MapPath("~/Images"), fileName);
file.SaveAs(location);
return Json("File uploaded"+acatext);
}
else
{
return Json("Failed");
}
}
如果需要,刪除[ValidateAntiForgeryToken]
,然后您必須手動將其添加到您的ajax標頭。
編輯使其工作按鈕單擊添加按鈕頁面<input type="button" value="upload" id="upload" />
,注冊點擊事件
<script type="text/javascript">
$('#upload').on('click', function (e) {
var fileform = document.getElementById('fileupload');
var files = fileform.files;
var text=$('#txtacademyname').val();
if (files.length > 0) {
var data = new FormData();
data.append("file", files[0]);
data.append("acatext", text);
console.log(data);
$.ajax({
type: "POST",
url: '@Url.Action("SaveAcademy","Academy")',
contentType: false,
processData: false,
data: data,
success: function (data) {
alert(data);
},
error: function () {
}
});
}
});
</script>
看一下這個
http://www.c-sharpcorner.com/UploadFile/b696c4/how-to-upload-and-display-image-in-mvc/
I hope it will be useful for you.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.