asp.net-mvc – 如何包括一个模型与RedirectToAction?

在下面的RedirectToAction中,我想传递一个viewmodel。如何将模型传递到重定向

我设置了一个断点来检查模型的值,以验证模型是否正确创建。它是正确的,但是结果视图不包含在模型属性中找到的值。

//
// model created up here...
//
return RedirectToAction("actionName","controllerName",model);

ASP.NET MVC 4 RC

解决方法

RedirectToAction向客户端浏览器返回302响应,因此浏览器将向响应的位置头值中的url发送一个新的GET请求。

如果您尝试将简单的瘦平面视图模型传递给第二个操作方法,则可以使用this overload的RedirectToAction方法

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,string controllerName,object routeValues
)

RedirectToAction会将传递的对象(r​​outeValues)转换为查询字符串,并将其附加到url(从我们传递的前两个参数生成),并将生成的url嵌入到响应的location头中。

让我们假设你的视图模型是这样的

public class StoreVm
{
    public int StoreId { get; set; }
    public string Name { get; set; }
    public string Code { set; get; } 
}

在你的第一个动作方法中,你可以将这个对象传递给RedirectToAction方法

var m = new Store { StoreId =101,Name = "Kroger",Code = "KRO"};
return RedirectToAction("Details","Store",m);

这个代码将发送一个302响应给浏览器,位置头值为

Store/Details?StoreId=101&Name=Kroger&Code=KRO

假设您的Details操作方法的参数的类型为StoreVm,那么querystring参数值将正确映射到参数的属性

public ActionResult Details(StoreVm model)
{
  // model.Name & model.Id will have values mapped from the request querystring
  // to do  : Return something. 
}

以上将适用于通过小扁平视图模型。但是如果你想传递一个复杂的对象,你应该尝试遵循PRG模式。

PRG模式

PRG代表POST – REDIRECT – GET。使用这种方法,您将在querystring中发出一个具有唯一ID的重定向响应,使用该重定向响应,第二个GET操作方法可以再次查询资源并向视图返回一些内容

int newStoreId=101;
return RedirectToAction("Details",new { storeId=newStoreId} );

这将创建url商店/详细信息?storeId = 101
并在您的详细信息GET操作中,使用传入的storeId,您将从某处(从服务或查询数据库等)获取/构建StoreVm对象,

public ActionResult Details(string storeId)
{
   // from the storeId value,get the entity/object/resource
   var store = yourRepo.GetStore(storeId);
   if(store!=null)
   {
      // Map the the view model
      var storeVm = new StoreVm { Id=storeId,Name=store.Name,Code=store.Code};
      return View(storeVm);
   }
   return View("StoreNotFound"); // view to render when we get invalid store id
}

TempData

跟着PRG pattern一个更好的解决方案来处理这个用例。但是如果你不想这样做,并且真的想跨越无状态HTTP请求传递一些复杂的数据,你可以使用一些临时存储机制,如TempData

TempData["NewCustomer"] = model;
return RedirectToAction("actionName","controllerName");

并再次在您的GET Action方法中读取它。

public ActionResult actionname()
{      
  var model=TempData["NewCustomer"] as Customer
  return View(model);
}

TempData使用场景后面的Session对象来存储数据。但一旦读取数据,数据终止。

Rachel写了一个漂亮的博客post解释什么时候使用TempData / ViewData。值得阅读。

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....