Ajax.BeginForm و ارسال فایل به سرور در ASP.NET MVC
نویسنده: وحید نصیری
تاریخ: ۱۳۹۳/۰۴/۲۱ ۸:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
@RenderBody()
</div>
<script src="~/Scripts/jquery-1.11.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/ajaxfileupload.js"></script>
@RenderSection("Scripts", required: false)
</body>
</html> namespace MVCAjaxFormUpload.Models
{
public class Product
{
public int Id { set; get; }
public string Name { set; get; }
}
} using System.Threading;
using System.Web;
using System.Web.Mvc;
using MVCAjaxFormUpload.Models;
namespace MVCAjaxFormUpload.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Product product)
{
var isAjax = this.Request.IsAjaxRequest();
return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult UploadFiles(HttpPostedFileBase image1, int id)
{
var isAjax = this.Request.IsAjaxRequest();
Thread.Sleep(3000); //شبیه سازی عملیات طولانی
return Json(new { FileName = "/Uploads/filename.ext" }, "text/html", JsonRequestBehavior.AllowGet);
}
}
} @model MVCAjaxFormUpload.Models.Product
@{
ViewBag.Title = "Index";
}
<h2>Ajax Form Upload</h2>
@using (Ajax.BeginForm(actionName: "Index",
controllerName: "Home",
ajaxOptions: new AjaxOptions { HttpMethod = "POST" },
routeValues: null,
htmlAttributes: new { id = "uploadForm" }))
{
<label>Name:</label>
@Html.TextBoxFor(model => model.Name)
<br />
<label>Image:</label>
<br />
<input type="file" name="Image1" id="Image1" />
<br />
<input type="submit" value="Submit" />
<img id="loading" src="~/Content/Images/loading.gif" style="display:none;">
}
@section Scripts
{
<script type="text/javascript">
$(function () {
$('#uploadForm').submit(function () {
$("#loading").show();
$.ajaxFileUpload({
url: "@Url.Action("UploadFiles", "Home")", // مسیری که باید فایل به آن ارسال شود
secureuri: false,
fileElementId: 'Image1', // آی دی المان ورودی فایل
dataType: 'json',
data: { id: 1, data: 'test' }, // اطلاعات اضافی در صورت نیاز
success: function (data, status) {
$("#loading").hide();
if (typeof (data.FileName) != 'undefined') {
alert(data.FileName);
}
},
error: function (data, status, e) {
$("#loading").hide();
alert(e);
}
});
});
});
</script>
} @using (Ajax.BeginForm(actionName: "Index",
controllerName: "Home",
ajaxOptions: new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "doUpload(data, status, xhr)"
},
routeValues: null,
htmlAttributes: new { id = "uploadForm" }))
{ function doUpload(data, status, xhr) {
alert(data.result);
// مابقی کدهای آپلود فایل • OnBegin – xhr • OnComplete – xhr, status • OnSuccess – data, status, xhr • OnFailure – xhr, status, error
<div>
<div style="margin: 2px 4px !important">
<div>
عکس 1
<input type="file" name="imageSrc" id="imageSrc" />
@*@Html.Kendo().Upload().Name("imageSrc").Multiple(false)*@
@Html.ValidationMessageFor(model => model.Image)
</div>
</div>
</div>
<div>
<div style="margin: 2px 4px !important">
<div>
عکس 2
<input type="file" name="imageSrc2" id="imageSrc2" />
@*@Html.Kendo().Upload().Name("imageSrc2").Multiple(false)*@
@Html.ValidationMessageFor(model => model.Image)
</div>
</div> با سلام؛ در صورتی که قصد ذخیره سازی اطلاعات یک محصول را داشته باشم و یکی از Propertyهای کلاس محصول ImageName باشد، باید نام عکس ارسالی را دریافت و دخیره کنیم، اکشن متد UpoadFiles نام عکس ذخیره شده را برگشت میدهد، حال به چه طریقی میتوان به این نام در اکشن متد Index دسترسی داشت؟ نام برگشتی از اکشن متد UploadFiles را در یک HiddenField قرار میدهم ولی باز هم در اکشن Index در دسترس نیست.
<div class="container-fluid">
@using (Ajax.BeginForm("Add", "Authors", new AjaxOptions { UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, HttpMethod = "POST" }, new { @class = "form-horizontal", id = "UploadFile" }))
{
@Html.AntiForgeryToken()
<div class="control-group">
<label class="control-label" for="AuhtorFirstNameAndLastName">نام نویسنده</label>
<div class="controls">
@Html.TextBoxFor(author => author.AuhtorFirstNameAndLastName, new { placeholder = "نام نویسنده" })
</div>
@Html.ValidationMessageFor(author => author.AuhtorFirstNameAndLastName)
</div>
<div class="control-group">
<label class="control-label" for="Status">ارسال عکس</label>
<div class="controls">
<input type="file" name="avatarFile" id="avatarFile" />
</div>
<div>
@*<input type="submit" name="btn-submit" value="ارسال" class="btn btn-success" />*@
<img id="loading" alt="1" src="Images/loading83.gif" style="display: none;" />
</div>
</div>
<div id="result"></div>
<input type="submit" name="btn-submit" value="افزودن نویسنده" class="btn btn-success" />
<input type="button" name="btn-colose" id="btn-close" value="انصراف" class="btn btn-danger" onclick="$dialog.dialog('close');" />
}
</div>
<script type="text/javascript">
$('#UploadFile').submit(function () {
$("#loading").show();
$.ajaxFileUpload({
url: "@Url.Action("AddAvatar","Authors")",
secureuri: false,
fileElementId: 'avatarFile',
dataType: 'json',
data: {},
success: function (data, status) {
$("#loading").hide();
},
error: function (data, status, e) {
$("#loading").hide();
}
});
});
</script>
jQuery.extend({
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || window, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}, <input type="file" name="Image1" id="Image1" multiple />
[HttpPost]
public ActionResult UploadFiles(HttpPostedFileBase[] image1, int id)
{
var isAjax = this.Request.IsAjaxRequest();
Thread.Sleep(3000);
return Json(new { FileName = "/Uploads/filename.ext" }, "text/html", JsonRequestBehavior.AllowGet);
}
formElementId: "uploadForm", // کدام فرم در صفحه پردازش شود؟
$("#" + formElementId + " > input[type='file']").each(function () {
var oldElement = $(this);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr("id", fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
});