使用C#ASP.NET MVC Pattern中的RedirectToAction将ViewData传递给ActionResult

时间:2015-01-16 19:58:05

标签: c# asp.net-mvc-4 design-patterns properties

我有一个表单,一旦提交,将根据与服务器端计算结合输入的内容进行一些复杂的路由。我想通过RedirectToAction将从第一个表单收集的数据传递给第二个表单。

起初我以为我可以执行RedirectToAction来干净地通过POST方法传递数据,但似乎没有简单的方法可以做到这一点。阅读更多我想知道是否有一些简单的方法我可以通过RedirectToAction将Hashtable或ViewData传递给正确的ActionResult并只读取变量,但事实证明这比我想象的更具挑战性。

这是我正在尝试的简化版本。

[AcceptVerbs("GET","POST")]
public ActionResult Step8(int id = 0, Hashtable FormValues = null) {

    // was this a redirect back to us?
    if (FormValues != null && FormValues.Count > 0) {
        if (FormValues.ContainsKey("title") && FormValues["title"] != null) {
            string _title = FormValues["title"].ToString();
        }
    }
    // the form in thie view redirects to Step9
    return View(); 
}

[AcceptVerbs("POST")]
public ActionResult Step9(int id = 0) {
    bool issue_found = true;

    if(issue_found){
        // hypothetical issue found, back to previous step
        Hashtable _FormValues = new Hashtable();
        _FormValues.Add("title", "My Title");
        _FormValues.Add("product", "My thing");
        return this.RedirectToAction("Step8", _FormValues);
    }else{
        // .. do stuff
        return View();
    }   
}

我做错了什么?我该如何传递这些数据?

1 个答案:

答案 0 :(得分:1)

这种方法比实际需要的要复杂得多。 TempData 幸存重定向,这就是我所做的。这是一个有效的解决方案:

[AcceptVerbs("GET","POST")]
public ActionResult Step8(int id = 0) {

    string _product = "";
    string _title = "";

    // was this a redirect back to us?
    try {
        if (TempData != null) {
            if (TempData.ContainsKey("product") && TempData["product"] != null) {
                _product = TempData["product"].ToString();
            }
            if (TempData.ContainsKey("title") && TempData["title"] != null) {
                _title = TempData["title"].ToString();
            }
        }
    } catch {}

    // The form in this view performs a POST to Step9
    return View(); 
}

[AcceptVerbs("POST")]
public ActionResult Step9(int id = 0) {
    bool issue_found = true;

    if(issue_found){
        // hypothetical issue found, back to previous step

        TempData["title"] = "My Title";
        TempData["product"] = "My thing";
        return this.RedirectToAction("Step8");
    }else{
        // .. do stuff
        return View();
    }   
}