【发布时间】:2015-08-29 22:15:27
【问题描述】:
我想使用 MVC 创建一个包含个人资料照片的注册表单。我不想在完成表单之前为人们添加记录(包括个人资料照片上传)。此外,我希望我的 UploadImage 视图和控制器对许多表单(不仅仅是这个表单)可重复使用。我通过ActionLink将三个变量传递给我的上传表单:RedirectAction (RA)、RedirectController (RC)和dataname,过程如下:
-
我将
RA, RC, dataname存储在ViewBag中,然后将它们放入hidden <input> tags以在发布文件时提交// GET: UploadImage/Upload public ActionResult Upload(string RA, string RC, string dataname) { ViewBag.RedirectAction = RA; ViewBag.RedirectController = RC; ViewBag.DataName = dataname; return View(); } -
将这些行放在我的 Upload.cshtml(视图)中:
@using (Html.BeginForm("Upload", "UploadImage", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" name="file" /> <input type="hidden" name="RA" value="@ViewBag.RedirectAction" /> <input type="hidden" name="RC" value="@ViewBag.RedirectController" /> <input type="hidden" name="dataname" value="@ViewBag.DataName" /> <input type="submit" name="Submit" id="Submit" value="Upload" /> } -
将
filename存储在TempData中,将dataname作为Key并重定向到/RC/RA:// POST: UploadImage/Upload/ [HttpPost] public ActionResult Upload(HttpPostedFileBase file, string RA , string RC , string dataname) { var filepath = "C:/myfilename.jpg"; TempData.Add(dataname, filepath); return RedirectToAction(RA,RC); } -
并通过在我的注册表单中使用
TempData来获取我的文件路径:@if (TempData.Keys.Contains("MyData")) { <div class="form-group"> <p>@TempData["MyData"].ToString()</p> </div>}
代码运行良好,但重要的警告是,当重定向到注册表单时,我不希望其他已完成的字段丢失。我该如何解决这个问题?
【问题讨论】:
-
有点明白你为什么这样做,而不是仅仅用表单上传文件 - 你所做的只是降低性能,如果用户刷新浏览器,你当前的
TempData方法将失败.如果由于某种原因您想在保存主表单之前单独上传文件,请使用 ajax(与FormData结合使用)或为此设计的众多 jquery 插件之一,并返回您可以存储的文件路径隐藏输入。
标签: c# asp.net-mvc redirect asp.net-mvc-5 tempdata