如何将模型数据传递给一个控制器到另一个控制器

时间:2015-01-05 06:06:37

标签: c# asp.net-mvc

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

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

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

        public ActionResult nextStep(StudentModel model)
        {           
            return View(model);
        }
nextStep控制器模型中的

为null。 怎么做? 我需要在nextStep conreoller中使用StudentModel数据。

1 个答案:

答案 0 :(得分:7)

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

<强> 1。 TempData的

您需要在TempData中保留模型并进行RedirectToAction。但是,限制是它仅适用于即时请求。在你的情况下,这不是一个问题。你可以用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,我们可以使用模型属性名称将数据作为Query字符串传递。 MVC模型绑定器将解析查询字符串并将其转换为模型。

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

另请注意 不建议在查询字符串中传递合理数据