簡體   English   中英

在C#ASP.NET MVC模式中使用RedirectToAction將ViewData傳遞給ActionResult

[英]Pass ViewData to ActionResult using RedirectToAction in C# ASP.NET MVC Pattern

我有一個表單,一旦提交,將根據與服務器端計算結合輸入的內容進行一些復雜的路由。 我想通過RedirectToAction將從第一種形式收集的數據傳遞給第二種形式。

起初我以為我可以執行RedirectToAction來干凈地通過POST方法傳遞數據,但是似乎沒有簡單的方法可以做到這一點。 閱讀更多內容我想看看是否有一些簡單的方法可以將Hashtable或ViewData通過RedirectToAction傳遞給正確的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();
    }   
}

我究竟做錯了什么? 如何傳遞這些數據?

該方法要復雜得多。 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();
    }   
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM