0

I'm working on a ASP.NET MVC system where you may click on a ajax link that will open a window (kendo window but it does not affect the situation) which a complex flow. To make this less of a nightmare to manage, I made a ViewModel (as I should) but this ViewModel is a complex object due to the complexity of the procedure.

There is anywhere from a single to 5 windows that asks various questions depending on a lot of conditions (including, but not limited to, what time you click the link, who you are, what schedule is attached to your account and, obviously, your previous answers in this flow).

The problem is that having a complex object, I cannot simply make @Html.HiddenFor(o=>o.XXX). So I proceeded to find an alternative and it led me with a single option, TempData. I'm really not a fan of dynamics and object types. I'd really like to have this View Model strongly typed.

What would be the best way to approach this?

4

1 回答 1

0

这是使用SessionorTempData可能有意义的情况。与流行的看法相反,您可以使这些有点强类型。不像视图模型,但您可以通过使用扩展方法来避免钥匙串混乱。

例如,不要做这样的事情:

TempData["NestedVariable1"] = someObject;
...
var someObject = TempData["NestedVariable1"] as CustomType;

您可以编写扩展方法来存储这些变量,并将键和转换封装在扩展方法中。

public static class ComplexFlowExtensions
{
    private static string Nv1Key = "temp_data_key";

    public static void NestedVariable1(this TempData tempData, CustomType value)
    {
        // write the value to temp data
        tempData[Nv1Key] = value;
    }

    public static CustomType NestedVariable1(this TempData tempData)
    {
        // read the value from temp data
        return tempData[Nv1Key] as CustomType;
    }
}

然后,您可以从控制器或视图中读取/写入这些值,如下所示:

TempData.NestedVariable1(someObject);
...
var someObject = TempData.NestedVariable1();

您也可以使用相同的模式Session。而不是将每个单独的标量值保存在单独的变量中,您应该能够将整个嵌套对象图存储在变量中。要么,要么将其序列化为 JSON 并存储,然后在将其取回时反序列化。无论哪种方式,我认为这比写入视图表单的大量隐藏字段要好。

于 2013-03-12T13:00:09.480 回答