在回发MVC后保留枚举值

时间:2016-06-14 15:55:50

标签: c# model-view-controller

查看

<input type="hidden" name="selectedValue" value="0" />
            <select name="itemType" id="itemType" style="width:80%;">
                <option value="Item1">Item 1</option>
                <option value="Item2">Item 2</option>
                <option value="Item3">Item 3</option>
                <option value="Item4">Item 4</option>
                <option value="Item5">Item 5</option>
            </select>

视图模型

public ItemTypes itemType { get; set; }

ItemTypes.cs中的枚举列表(扩展方法)

public enum ItemTypes
{
    Item1,
    Item2,
    Item3,
    Item4,
    Item5
}


public static string GetItemDesc(this ItemTypes itemtype)
    {
        switch (itemtype)
        {
            case ItemTypes.Item1:
                return "Item 1 Description";

            case ItemTypes.Item2:
                return "Item 2 Description";

            case ItemTypes.Item3:
                return "Item 3 Description";

            default:
                return "Item 4 and 5 Description";
        }
    }

以上是我的代码。我想在整个页面中保留选定的Enum值。我有四个,索引(下拉菜单所在的位置),您选择付款方式的页面,验证页面(您验证所有信息的位置)和收据页面(表明您的交易有已成功。)我需要枚举值在每个页面保持不变。请帮忙。

2 个答案:

答案 0 :(得分:1)

在我看来,您需要做的是将选择内容保存在某处,以便其他页面可以访问该选择。 MVC是无状态的,因此值需要在每次调用中传递,或者需要保存在其他页面可以访问它的位置。您可以采用多种方法来保存和检索浏览器控件的选择。

请记住,默认情况下枚举将序列化为整数,因此在处理客户端的值时,它将是一个整数。这意味着在您的视图中,您可能需要使用<option value="0">Item 1</option>使用0,1,2,3和4作为客户端值 - 或者使用MVC HTML帮助程序或Razor标记,具体取决于您的MVC版本,使用枚举名称为您生成这些选项。

以下是一些可能符合您需求的保存/检索选项:

  • 当您提交每个页面时,将选择值作为发布内容的属性(您的itemType),然后在加载下一页时,将值包含在查询字符串中,或​​作为一部分下一个获取请求的路由(GetPaymentMethodPage,GetVerifyPage,GetReceiptPage)。

  • 将选择值保存在Cookie中,并在JavaScript中从该Cookie中检索(如果Cookie不存在,已删除或用户不允许Cookie,则需要提供默认值)。

  • 将选择值保存在浏览器存储中 - 有各种类型,包括Web存储(SessionStorage或LocalStorage)。

答案 1 :(得分:0)

您有几个不同的选择,但请记住,MVC是无状态的。这意味着MVC不了解页面请求中存储在枚举中的任何信息。因此,您需要将参数传递给以字符串形式接收枚举的操作方法,然后将字符串解析回枚举类型。如何执行此操作的示例是here

或复制+粘贴的代码:

using System;

[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };

public class Example
{
   public static void Main()
   {
      string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
      foreach (string colorString in colorStrings)
      {
         try {
            Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);        
            if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))  
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
            else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
         }
         catch (ArgumentException) {
            Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
         }
      }
   }
}

还有一个事实是,您想要枚举的任何页面都需要从生成视图的操作方法传递枚举。然后在视图中,您必须接受并将枚举存储在隐藏字段中。

相关问题