How to get the Model from an ActionResult?

前端 未结 4 930
既然无缘
既然无缘 2020-12-30 23:25

I\'m writing a unit test and I call an action method like this

var result = controller.Action(123);

result is ActionResult and

4条回答
  •  有刺的猬
    2020-12-30 23:41

    We placed the following piece in a testsbase.cs allowing for typed models in the tests a la

    ActionResult actionResult = ContextGet();
    var model = ModelFromActionResult(actionResult);
    

    ModelFromActionResult...

    public T ModelFromActionResult(ActionResult actionResult)
    {
        object model;
        if (actionResult.GetType() == typeof(ViewResult))
        {
            ViewResult viewResult = (ViewResult)actionResult;
            model = viewResult.Model;
        }
        else if (actionResult.GetType() == typeof(PartialViewResult))
        {
            PartialViewResult partialViewResult = (PartialViewResult)actionResult;
            model = partialViewResult.Model;
        }
        else
        {
            throw new InvalidOperationException(string.Format("Actionresult of type {0} is not supported by ModelFromResult extractor.", actionResult.GetType()));
        }
        T typedModel = (T)model;
        return typedModel;
    }
    

    An example using a Index page and List:

    var actionResult = controller.Index();
    var model = ModelFromActionResult>((ActionResult)actionResult.Result);
    

提交回复
热议问题