如何将模型数据传递到一个控制器到另一个控制器 [英] How to pass model data to one controller to another controller

查看:170
本文介绍了如何将模型数据传递到一个控制器到另一个控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将模型数据传递到一个控制器到另一个控制器吗?

pass model data to one controller to another controller is possible?

我想将模型数据传递给一个控制器或另一个控制器.

I want to passe the model data to one controller ro another controller.

[HttpPost]
        public ActionResult Personal(StudentModel student)
        {                          
                return RedirectToAction("nextStep", new { model = student});          
        }

        public ActionResult nextStep(StudentModel model)
        {           
            return View(model);
        }

nextStep控制器型号中的

为空. 怎么做? 我需要在nextConreoller中获取StudentModel数据.

in nextStep controller model value is null. How to do it? I need to StudentModel data in nextStep conreoller.

推荐答案

您正在使用RedirectToAction.它将发出GET请求.您可以通过两种方式在此处传递模型.

You are using RedirectToAction. It will issue GET request. There are two ways you can pass your model here.

1. TempData

您需要将模型保留在TempData中并制作RedirectToAction.但是,限制是它仅可用于立即请求.就您而言,这不是问题.您可以使用TempData

You need to persist the model in TempData and make RedirectToAction. However the restriction is it will be available only for the immediate request. In your case, it is not a problem. You can do it with TempData

public ActionResult Personal(StudentModel student)
{                          
       TempData["student"] = student;
       return RedirectToAction("nextStep", "ControllerName");          
}

public ActionResult nextStep()
{      
       StudentModel model= (StudentModel) TempData["student"];
       return View(model);
}

2.传递查询字符串

由于请求是GET,我们可以将数据作为带有模型属性名称的查询字符串进行传递. MVC模型绑定程序将解析查询字符串并将其转换为模型.

As the request is GET, we can pass the data as Query string with the model property name. MVC model binder will resolve the query string and convert it as model.

 return RedirectToAction("nextStep", new { Name = model.Name, Age=model.Age });

也请注意 不建议在查询字符串中传递敏感数据 .

Also take a note passing sensible data in a Query string is not advisable.

这篇关于如何将模型数据传递到一个控制器到另一个控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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