4

redirectActionを使用してアクション間でデータを送信するにはどうすればよいですか?

私はPRGパターンを使用しています。そして、私はそのようなものを作りたいです

[HttpGet]
    [ActionName("Success")]
    public ActionResult Success(PersonalDataViewModel model)
    {
        //model ko
        if (model == null)
            return RedirectToAction("Index", "Account");

        //model OK
        return View(model);
    }

    [HttpPost]
    [ExportModelStateToTempData]
    [ActionName("Success")]
    public ActionResult SuccessProcess(PersonalDataViewModel model)
    {

        if (!ModelState.IsValid)
        {
            ModelState.AddModelError("", "Error");
            return RedirectToAction("Index", "Account");
        }

        //model OK
        return RedirectToAction("Success", new PersonalDataViewModel() { BadgeData = this.GetBadgeData });
    }
4

3 に答える 3

9

リダイレクトする場合、渡すことができるのはクエリ文字列値のみです。複雑なオブジェクト全体ではありません:

return RedirectToAction("Success", new {
    prop1 = model.Prop1,
    prop2 = model.Prop2,
    ...
});

これは、スカラー値でのみ機能します。したがって、必要なすべてのプロパティをクエリ文字列に含める必要があります。そうしないと、リダイレクトで失われます。

もう1つの可能性は、モデルをサーバー上のどこかに(データベースなど)永続化し、リダイレクトするときにモデルを取得できるIDのみを渡すことです。

int id = StoreModel(model);
return RedirectToAction("Success", new { id = id });

そして、Successアクション内で、モデルを取得します。

public ActionResult Success(int id)
{
    var model = GetModel(id);
    ...
}

さらに別の可能性はTempData、個人的にはお勧めしませんが、使用することです。

TempData["model"] = model;
return RedirectToAction("Success");

アクション内でSuccessそれをフェッチしTempDataます:

var model = TempData["model"] as PersonalDataViewModel;
于 2012-05-25T09:51:08.907 に答える
2

Darinが述べたように、オブジェクトを使用してアクション間でデータを渡すことはできません。渡すことができるのはスカラー値のみです。

データが大きすぎる場合、またはスカラー値のみで構成されていない場合は、次のようにする必要があります

[HttpGet]
public ActionResult Success(int? id)
{
    if (!(id.HasValue))
        return RedirectToAction("Index", "Account");

    //id OK
    model = LoadModelById(id.Value);
    return View(model);
}

そしてそれidRedirectToAction

    return RedirectToAction("Success", { id = Model.Id });
于 2012-05-25T09:54:07.050 に答える
0

RedirectToActionメソッドはHTTP 302ブラウザーに応答を返します。これにより、ブラウザーGETは指定されたアクションを要求します。したがって、複雑なオブジェクトを使用して他のメソッドを呼び出すように、複雑なオブジェクトを渡すことはできません。

考えられる解決策は、GETアクションでIDを渡して、オブジェクトを再構築できるようにすることです。このようなもの

[HttpPost]
public ActionResult SuccessProcess(PersonViewModel model)
{
  //Some thing is Posted (P) 
  if(ModelState.IsValid)
  {
    //Save the data and Redirect (R)
    return RedirectToAction("Index",new { id=model.ID});
  }
  return View(model)
}

public ActionResult Index(int id)
{
  //Lets do a GET (G) request like browser requesting for any time with ID
  PersonViewModel model=GetPersonFromID(id);
  return View(id);
}

}

セッションを使用して、この投稿とGETリクエストの間にデータ(複合オブジェクト)を保持することもできます(TempDataは内部的にセッションを使用しています)。しかし、私はそれがPRGパターンの純粋さを奪うと信じています。

于 2012-05-25T09:53:24.970 に答える