我有一个问题。 我使用Kendo UI for ASP.NET MVC为我的Web应用程序创建上传功能。它工作得很好,但问题是用户在点击上传按钮后执行提交表单并导航到其他页面之前无法查看他们上传的文件。在这种情况下,我在Create View中放置了一个上传器,我希望在将文件上传到服务器之后,我会将该文件的链接存储到db中我的模型的字段中,但它总是得到null值。这里的任何人都可以给我一些建议去做。非常感谢。这是我使用的代码。 *控制器:
[HttpPost]
public ActionResult Create(Model model)
{
if(ModelState.IsValid)
{
model.Url = Url;
Db.Models.Add(model);
Db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
// The Name of the Upload component is "attachments"
foreach (var file in attachments)
{
// Some browsers send file names with full path. We only care about the file name.
var fileName = Path.GetFileName(file.FileName);
var destinationPath = Path.Combine(Server.MapPath("~/Contents/files/"), fileName);
DestinationPath = destinationPath;
file.SaveAs(destinationPath);
}
// Return an empty string to signify success
return Content("");
}
查看
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<div class="editor-label">
Upload file
</div>
<div style="width:45%">
@Html.Kendo().Upload().Name("attachments").Async(async => async.Save("Save", "Model").AutoUpload(true)).Multiple(false)
</div>
<p>
<input type="submit" value="Create" class="k-button" />
</p>
模型
public string Url {get;set;}
答案 0 :(得分:5)
客户端代码:
@(Html.Kendo().Upload()
.Name("uploadTagImage")
.Multiple(false)
.Async(async => async.Save("ApiUploadImage", "Tag").SaveField("files").AutoUpload(true))
.Events(events =>
{
events.Success("PV_Upload_TagImage_OnSuccess");
})
)
<script type="text/javascript">
// Events
PV_Upload_TagImage_OnSuccess = function (result) {
var data = result.response.Data;
if(data.length > 0) {
$("#tag-image").attr('src', data[0]);
}
$.publish("PV_Grid_Access_OnAddNewRecord_Event");
};
</script>
服务器端代码:
public ActionResult ApiUploadImage([DataSourceRequest] DataSourceRequest request, IEnumerable<HttpPostedFileBase> files)
{
var savedFilePaths = new List<string>();
var applicationPath = System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Authority + System.Web.HttpContext.Current.Request.ApplicationPath + "/Content/Images/Others/";
if(files != null)
{
foreach(var file in files)
{
var fileName = Path.GetFileName(file.FileName);
if(fileName !=null)
{
fileName = DateTime.Now.ToString("yyyyMMddmm-") + fileName;
var imagePath = Path.Combine(Server.MapPath("~/Content/Images/Others/"), fileName);
file.SaveAs(imagePath);
savedFilePaths.Add(applicationPath + fileName);
}
}
}
return Json(new[] {savedFilePaths}.ToDataSourceResult(request));
}
答案 1 :(得分:1)
您不必返回空字符串。您可以返回任何所需的字符串值。
为此,您需要将响应内容类型设置为&#34; text / plain&#34;。
Response.ContentType = "text/plain";