我们可以在 RedirectToAction 中将模型作为参数传递吗? [英] Can we pass model as a parameter in RedirectToAction?

查看:20
本文介绍了我们可以在 RedirectToAction 中将模型作为参数传递吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to know, there is any technique so we can pass Model as a parameter in 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 中传递学生模型吗?

推荐答案

使用 TempData

代表一组数据,只从一个请求到下一个

Represents a set of data that persists only from one request to the next

[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();
}

替代方式使用查询字符串传递数据

Alternative way Pass the data using Query string

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

这将生成一个 GET 请求,如 Student/GetStudent?Name=John &类=clsz

This will generate a GET Request like Student/GetStudent?Name=John & Class=clsz

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

Ensure the method you want to redirect to is decorated with [HttpGet] as the above RedirectToAction will issue GET Request with http status code 302 Found (common way of performing url redirect)

这篇关于我们可以在 RedirectToAction 中将模型作为参数传递吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆