Pass an object in RedirectToAction() using T4MVC [duplicate]

点点圈 提交于 2019-12-13 17:56:01

问题


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:


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);
}


来源:https://stackoverflow.com/questions/11111555/pass-an-object-in-redirecttoaction-using-t4mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!