簡體   English   中英

如何將 RedirectToAction 中的單個參數傳遞給 ASP .NET MVC 中的不同 controller?

[英]How to pass single parameter in RedirectToAction to different controller in ASP .NET MVC?

我知道,之前有人問過類似的問題。 但我找不到完全相同的案例。 我想將 model object 作為回報 RedirectToAction() 傳遞給另一個 controller 中的方法。 我的代碼:

  MyModel mdl_obj=new MyModel();
  return RedirectToAction("mthdInAnotherController", "AnotherControllerName",new { mdl_obj = mdl_obj });

我將一些值分配給 model object 並將其發送到另一個 controller 中的方法。 但是那個方法有不止一個 arguments 我沒有通過那些。 While passing, model object is not null but in another controller, I am getting null value for model object. 可能是什么原因?

TempData 適用於這種情況。 TempData 用於將數據從視圖傳輸到 controller、controller 到視圖,或從一種操作方法傳輸到相同或不同 controller 的另一種操作方法。

用法是

    public ActionResult Foo()
    {
        // Store data into the TempData that will be available during a single redirect
        TempData["Model"] = new MyModel();
    
        // If you store something into TempData and redirect to a controller action that will be available to consume the data
        return RedirectToAction("bar");
    }
    
    public ActionResult Bar()
    {
        var mdl_obj = TempData["Model"];
        ...
    }

參考: ViewBag、ViewData 和 TempData

您首先需要檢查 model class 是否在您的 HTML 視圖中聲明,如下所示:

@model MyModel

沒有它,視圖將無法綁定來自 controller 的數據。

視圖中聲明的 model class 必須與 Z594C103F2C6E04C0CAZAB059F03E 方法返回的 class 匹配:

[HttpGet]
public ActionResult mthdInAnotherController(string param1, string param1, ..., paramN)
{
    MyModel = new MyModel();
    // populate model here
    ...
    ...
    return View(myModel);
}

還要檢查調用的 controller 方法是否具有與 RedirectToAction() 參數 object 匹配的輸入參數名稱:

return RedirectToAction("mthdInAnotherController", "AnotherControllerName", 
    new { 
        param1 = val1, param2 = val2, ... ,paramN = valN 
    });

暫無
暫無

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

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