【问题标题】:Can we pass model as a parameter in RedirectToAction?我们可以在 RedirectToAction 中将模型作为参数传递吗?
【发布时间】:2014-03-19 12:21:47
【问题描述】:

我想知道,有什么技术可以让我们将Model作为参数传递给RedirectToAction

例如:

public class Student{
    public int Id{get;set;}
    public string Name{get;set;}
}

控制器

public class StudentController : Controller
{
    public ActionResult FillStudent()
    {
        return View();
    }
    [HttpPost]
    public ActionResult FillStudent(Student student1)
    {
        return RedirectToAction("GetStudent","Student",new{student=student1});
    }
    public ActionResult GetStudent(Student student)
    {
        return View();
    }
}

我的问题 - 我可以在 RedirectToAction 中传递学生模型吗?

【问题讨论】:

  • 当然,这是一个有效的调用。没有路由吗?
  • 我试过这个但是没有找到模型值
  • 由于路由字典处理对象,请尝试将GetStudent 操作更改为接受object 并在内部将其转换为Student。另一种选择是在从FillStudent 传递它时使用 JSON 对其进行序列化。
  • @AndreiV 我在FillStudent获得模型价值
  • 这似乎是 ASP.NET MVC 开箱即用应该支持的基本操作,但仍然不可能。我不得不求助于从我的模型中提取值来创建一个路由值对象,只是为了通过从多个参数中提取将它们重新插入到我的 GET 处理程序中的模型中。

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 controller


【解决方案1】:

使用TempData

表示仅从一个请求持续到 下一个

[HttpPost]
public ActionResult FillStudent(Student student1)
{
    TempData["student"]= new Student();
    return RedirectToAction("GetStudent","Student");
}

[HttpGet]
public ActionResult GetStudent(Student passedStd)
{
    Student std=(Student)TempData["student"];
    return View();
}

另一种方式 使用查询字符串传递数据

return RedirectToAction("GetStudent","Student", new {Name="John", Class="clsz"});

这将生成一个像Student/GetStudent?Name=John & Class=clsz这样的GET请求

确保您要重定向到的方法用[HttpGet] 修饰为 上面的 RedirectToAction 将发出带有 http 状态的 GET 请求 找到代码302(执行url重定向的常用方法)

【讨论】:

  • 我不想使用TempData。我知道我们可以使用 TempData 来实现。但我的问题不同
  • 我也知道方法 2,但我的问题不同我可以实现我的问题 Yes/No
  • @AmitAgrawal,简单的NO。检查Passing Data in an ASP.NET MVC Application
  • 这是一个旧线程,但我想指出 1) GetStudent 操作在使用 TempData 时不需要有参数 2) 必须注意,如果这是为了实现PRG 模式,它仍然只能部分解决问题。在第二次刷新视图时,TempData 将是空的(按设计)!
  • @akd 大声笑吗?远离 Sessions 或 TempData?您描述的问题仅在禁用 ARR 关联性时与 Azure 有关。如果您需要 有状态 解决方案(几乎任何允许您登录的 Web 应用程序),那么 TempData 和 Sessions 绝对 是必需的。
【解决方案2】:

无需redirect to action 或new 关键字即可调用该操作。

 [HttpPost]
    public ActionResult FillStudent(Student student1)
    {
        return GetStudent(student1); //this will also work
    }
    public ActionResult GetStudent(Student student)
    {
        return View(student);
    }

【讨论】:

  • 什么是return GetStudent(student1)
  • Action GetStudent 必须返回 View 'GetStudent' 和模型学生 - 为我工作 - return View("GetStudent", student)
  • 这个答案对我不起作用(页面永远不会改变),但 hotfusions 评论可以。
  • 请注意,虽然这有效(@hotfusion 提到的更改)但这仍然不符合 PRG 模式。如果用户按 F5,他们将再次复制原始请求!
  • 这将显示原始请求的 url。这可能不是我们想要的。
【解决方案3】:

是的,您可以通过使用显示的模型

return RedirectToAction("GetStudent", "Student", student1 );

假设student1 是Student 的一个实例

这将生成以下网址(假设您使用默认路由并且student1 的值是ID=4 和Name="Amit")

.../Student/GetStudent/4?Name=Amit

在内部,RedirectToAction() 方法通过使用模型中每个属性的 .ToString() 值来构建 RouteValueDictionary。但是,只有当模型中的所有属性都是简单属性时,绑定才会起作用,并且如果任何属性都是复杂对象或集合,则绑定会失败,因为该方法不使用递归。例如,如果Student 包含属性List<string> Subjects,则该属性将导致查询字符串值为

....&Subjects=System.Collections.Generic.List'1[System.String]

绑定将失败,该属性将为null

【讨论】:

  • 感谢您在使用 RedirectToAction 时不将复杂对象、列表或集合包含到模型中的说明。这就是为我解决的问题。
  • 我支持这个。感谢您对复杂对象的说明。我们试图拒绝一个巨大的模型(大约 200 个字段),其中一个是 List()。重定向时我们收到大约 20 个转换字符串到 int 的错误,甚至显示错误源是什么也无济于事。
【解决方案4】:
  [HttpPost]
    public async Task<ActionResult> Capture(string imageData)
    {                      
        if (imageData.Length > 0)
        {
            var imageBytes = Convert.FromBase64String(imageData);
            using (var stream = new MemoryStream(imageBytes))
            {
                var result = (JsonResult)await IdentifyFace(stream);
                var serializer = new JavaScriptSerializer();
                var faceRecon = serializer.Deserialize<FaceIdentity>(serializer.Serialize(result.Data));

                if (faceRecon.Success) return RedirectToAction("Index", "Auth", new { param = serializer.Serialize(result.Data) });

            }
        }

        return Json(new { success = false, responseText = "Der opstod en fejl - Intet billede, manglede data." }, JsonRequestBehavior.AllowGet);

    }


// GET: Auth
    [HttpGet]
    public ActionResult Index(string param)
    {
        var serializer = new JavaScriptSerializer();
        var faceRecon = serializer.Deserialize<FaceIdentity>(param);


        return View(faceRecon);
    }

【讨论】:

  • 您能否说明您是如何在视图中使用 faceRecon 的?
【解决方案5】:
[NonAction]
private ActionResult CRUD(someModel entity)
{
        try
        {
            //you business logic here
     return View(entity);
       }                                
         catch (Exception exp)
         {
             ModelState.AddModelError("", exp.InnerException.Message);
             Response.StatusCode = 350;
             return someerrohandilingactionresult(entity, actionType);
         }
         //Retrun appropriate message or redirect to proper action
      return RedirectToAction("Index");   
}

【讨论】:

  • 因为您应该提供错误处理程序。但是我不确定它应该如何回答这个问题。
【解决方案6】:

我确实找到了类似的东西,有助于摆脱硬编码的临时数据标签

public class AccountController : Controller
{
    [HttpGet]
    public ActionResult Index(IndexPresentationModel model)
    {
        return View(model);
    }

    [HttpPost]
    public ActionResult Save(SaveUpdateModel model)
    {
        // save the information

        var presentationModel = new IndexPresentationModel();

        presentationModel.Message = model.Message;

        return this.RedirectToAction(c => c.Index(presentationModel));
    }
}

【讨论】:

  • 这个方法是从哪里来的? "this.RedirectToAction"
  • 好吧,控制器有那个方法:)
  • 我找不到 RedirectToAction 的重载 taht 采用 lambda 表达式。您确定它在 System.Web.Mvc 中,而不是在您使用的第三方库或扩展方法中吗?
猜你喜欢
  • 1970-01-01
  • 2015-12-29
  • 2021-02-02
  • 2017-09-19
  • 2011-07-24
  • 2018-10-11
  • 1970-01-01
  • 2016-12-17
相关资源
最近更新 更多