[英]Redirect back with message after file upload MVC 4 c#
我正在开发MVC 4应用程序,并希望重定向回带有消息以调用操作视图:
public class HospitalController: Controller { public ActionResult Index() { return View(Model); } [HttpPost] public ActionResult Index(Model model) { return View(ohosDetailFinal); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Upload(HttpPostedFileBase upload,FormCollection form) { //Here i want to pass messge after file upload and redirect to index view with message // return View(); not working } }
@using (Html.BeginForm("Upload", "Hospital", null, FormMethod.Post, new { enctype = "multipart/form-data", @class = "" })) { @Html.AntiForgeryToken() @Html.ValidationSummary() <input type="file" id="dataFile" name="upload" class="hidden" /> }
谢谢 !
遵循PRG模式。 成功处理后,将用户重定向到另一个GET操作。
您可以使用RedirectToAction
方法返回RedirectToAction
。 这将向浏览器返回304响应,并在位置标头中添加新的url,浏览器将对该URL发出新的GET请求。
[HttpPost]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//to do : Upload
return RedirectToAction("Index","Hospital",new { msg="success"});
}
现在,在“索引”操作中,您可以添加此新参数msg
并检查其值并显示适当的消息。 重定向请求将具有带有键msg的查询字符串(例如: /Hospital/Index?msg=success
)
public ActionResult Index(string msg="")
{
//to do : check value of msg and show message to user
ViewBag.Msg = msg=="success"?"Uploaded successfully":"";
return View();
}
并认为
<p>@ViewBag.Msg</p>
如果您不喜欢url中的querystring,则可以考虑使用TempData 。 但是tempdata仅可用于下一个请求。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
return Index();//or with model index
}
尝试下面的代码,希望对您有所帮助。
视图
@using (Html.BeginForm("Upload", "Hospital", null, FormMethod.Post, new { enctype = "multipart/form-data", @class = "" }))
{
if (TempData["Info"] != null)
{
@Html.Raw(TempData["Info"])
}
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<input type="file" id="dataFile" name="upload" class="hidden" />
}
控制者
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload,FormCollection form)
{
//Here i want to pass messge after file upload and redirect to index view with message
TempData["Info"]="File Uploaded Successfully!";
return RedirectToAction("Index");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.