Csharp/C#教程:将模型对象传递给RedirectToAction而不会污染URL?分享


将模型对象传递给RedirectToAction而不会污染URL?

这是我正在尝试做的事情:

public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(ContactModel model) { if (ModelState.IsValid) { // Send email using Model information. return RedirectToAction("Gracias", model); } return View(model); } public ActionResult Gracias(ContactModel model) { return View(model); } 

所有三种操作方法都在同一个控制器中。 基本上,用户在联系表单中键入一些数据,我想使用他们在Model对象中的名称将它们重定向到感谢页面。

代码是,它可以工作,但URL与GET变量一起传递。 不理想。

 https://localhost:7807/Contacto/Gracias?Nombre=Sergio&Apellidos=Tapia&Correo=opiasdf&Telefono=oinqwef&Direccion=oinqef&Pais=oinqwef&Mensaje=oinqwef 

有什么建议?

听起来像TempData的解决方案!

 [HttpPost] public ActionResult Index(ContactModel model) { if (ModelState.IsValid) { // Send email using Model information. TempData["model"] = model; return RedirectToAction("Gracias"); } return View(model); } public ActionResult Gracias() { ContactModel model = (ContactModel)TempData["model"]; return View(model); } 

快速回答是不传递整个模型,而是可以使用一些标识符从存储库中检索模型:

 [HttpPost] public ActionResult Index(ContactModel model) { if (ModelState.IsValid) { // Send email using Model information. return RedirectToAction("Gracias", model.ID); } return View(model); } public ActionResult Gracias(int contactID) { ContactModel model = new ContractRepository().GetContact(contactID); return View(model); } 

而不是做

 return RedirectToAction("Gracias", model); 

你可以做到

 [HttpPost] public ActionResult Index(ContactModel model) { if (ModelState.IsValid) { // Send email using Model information. return View("Gracias", model); } return View(model); } 

并删除您的Gracias控制器操作。 使用上面的“Gracias”视图将与您的ContactModel模型一起显示。

如果它使用相同的模型并且是工作流ex的锁定步骤部分,我认为不需要单独的控制器操作。 “成功发布到索引将始终导致显示Gracias视图”

您还可以将模型存储在TempData中(这类似于1请求会话状态)但我认为在您的情况下没有任何意义,因为它只会使事情复杂化

思考?

没有重定向,这不是很容易做到的吗?

这就是我所拥有的:

  [HttpGet] public ActionResult Contact() { return View(); } [HttpPost] public ActionResult Contact(EmailResponse response) { if(ModelState.IsValid){ return View("Thanks", response); } else { return View(); } } 

"Thanks"视图是EmailResponse强类型

上述就是C#学习教程:将模型对象传递给RedirectToAction而不会污染URL?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1024604.html

(0)
上一篇 2022年1月8日
下一篇 2022年1月8日

精彩推荐