C# 回发MVC后保留枚举值
看法 ItemTypes.cs中的枚举列表(扩展方法)C# 回发MVC后保留枚举值,c#,model-view-controller,C#,Model View Controller,看法 ItemTypes.cs中的枚举列表(扩展方法) 上面是我的代码。我希望在整个页面中保留选定的枚举值。我有四个,索引(下拉菜单所在)、选择付款方式的页面、验证页面(验证输入的所有信息)和收据页面(显示交易成功)。我需要枚举值在每页中保持不变。请提供帮助。您有一些不同的选择,但请记住MVC是无状态的。这意味着MVC不知道跨页面请求存储在枚举中的任何信息。因此,您需要将参数传递到将枚举作为字符串接收的操作方法中,然后将字符串解析回枚举类型。你可以这样做的一个例子是 或复制+粘贴的代码: pub
上面是我的代码。我希望在整个页面中保留选定的枚举值。我有四个,索引(下拉菜单所在)、选择付款方式的页面、验证页面(验证输入的所有信息)和收据页面(显示交易成功)。我需要枚举值在每页中保持不变。请提供帮助。您有一些不同的选择,但请记住MVC是无状态的。这意味着MVC不知道跨页面请求存储在枚举中的任何信息。因此,您需要将参数传递到将枚举作为字符串接收的操作方法中,然后将字符串解析回枚举类型。你可以这样做的一个例子是 或复制+粘贴的代码:
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";
}
}
还有一个事实,您希望接受枚举的任何页面都需要从生成视图的操作方法传递枚举。然后在视图本身中,您必须接受枚举并将其存储在隐藏字段中。在我看来,您需要做的是将选择保存在某个位置,以便其他页面可以访问该选择。MVC是无状态的,因此值需要在每次调用中传递,或者需要保存在其他页面可以访问的位置。有几种方法可以用来保存和检索浏览器控件的选择 请记住,默认情况下枚举将序列化为整数,因此在客户端处理值时,它将是整数。这意味着在视图中,您可能需要使用
项1
使用0、1、2、3和4作为客户端值,或者使用MVC HTML帮助程序或Razor标记,具体取决于您的MVC版本,以便使用枚举名称为您生成这些选项
以下是一些适合您需要的保存/检索选项:
- 提交每页时,将选择值作为发布内容的属性传递(您的
),然后在加载下一页时,将该值包含在查询字符串中,或作为下一个get请求(GetPaymentMethodPage、GetVerifyPage、GetReceiptPage)的路由的一部分itemType
- 将选择值保存在cookie中,并在JavaScript中从该cookie中检索它(如果cookie不存在、已删除或用户不允许cookie,则需要提供默认值)
- 将选择值保存在浏览器存储中-有多种类型,包括Web存储(会话存储或本地存储)
public ItemTypes itemType { get; set; }
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";
}
}
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);
}
}
}
}