Pass an object in RedirectToAction() using T4MVC [

2019-08-15 12:18发布

Possible Duplicate:
pass data from Action To Another Action

I have a view in which I submit a form and depending on the results I want to redirect to an action. The view that correspondes to and action is strongly-typed and it should accept a ResultsViewModel.

I'm trying to pass the ResultsViewModel using T4MVC.

Below is the code:

    [HttpPost]
    public virtual ActionResult AddEntity(string viewModel)
    {
        //Deserialize using Json.NET
        var entity = JsonConvert.DeserializeObject<MyEntity>(viewModel);

        var success = DoSomething(); //returns boolean
        if(success)
        {
            var result = new ResultsViewModel { MyEntity = entity, MessageId = 1};
            return RedirectToAction(MVC.MyController.ResultsPage(result));
        }

        var result = new ResultsViewModel { MyEntity = entity, MessageId = 2};
        return RedirectToAction(MVC.MyController.ResultsPage(result));
    }

    public virtual ActionResult ResultsPage(ResultsViewModel viewModel)
    {
        return View(viewModel);
    }

When the code reaches

    public virtual ActionResult ResultsPage(ResultsViewModel viewModel)
    {
        return View(viewModel);
    }

viewModel is always equal to null.

I know I can do something like this:

return RedirectToAction("ResultsPage", new { viewModel = result });

EDIT: I tried the return RedirectToAction("ResultsPage", new { viewModel = result }); and I'm also getting a null in my viewModel.

However I'm trying to figure out why/how to pass an object using T4MVC.

Thanks,

1条回答
孤傲高冷的网名
2楼-- · 2019-08-15 12:33

Use TempData

[HttpPost]
public virtual ActionResult AddEntity(string viewModel)
{
    //Deserialize using Json.NET
    var entity = JsonConvert.DeserializeObject<MyEntity>(viewModel);

    var success = DoSomething(); //returns boolean
    if(success)
    {
        var result = new ResultsViewModel { MyEntity = entity, MessageId = 1};
        return RedirectToAction(MVC.MyController.ResultsPage(result));
    }

    var result = new ResultsViewModel { MyEntity = entity, MessageId = 2};

    TempData["Result"] = result;


    return RedirectToAction(MVC.MyController.ResultsPage(result));
}

public virtual ActionResult ResultsPage()
{
    ResultsViewModel model = (ResultsViewModel)TempData["Result"];
    return View(model);
}
查看更多
登录 后发表回答