保留asp.net中的枚举值

时间:2013-09-25 17:33:34

标签: c# asp.net enums postback viewstate

我有一个asp.net页面,其中我使用枚举(在app_code中的类文件中定义了属性)

现在我的问题是每当页面获得回发时,属性中枚举的值被重置为第一个

我甚至尝试将该属性设置为静态,但仍然没有帮助。

下面是

我的枚举和属性声明:

private static UrlType _type;
public static UrlType UrlPattern
{
    get
    {
        HttpContext.Current.Response.Write("GET: " +_type + "<br>");
        return _type;
    }
    set
    {
        _type = value;
        HttpContext.Current.Response.Write("SET : " +_type + "<br>");
    }
}
public int VanityId { get; set; }
public enum UrlType
{
    ArticleOnly,
    ArticleCategoryCombination,
    Normal,
    TechForum
}

这就是我所说的:

public void BindRewrite()
{
    GrdRewrite.DataSource = objVanity.GetAllRewriteVanities(Vanity.UrlPattern);
    GrdRewrite.DataBind();
    if (Vanity.UrlPattern == Vanity.UrlType.ArticleCategoryCombination)
    {
        GrdRewrite.Columns[2].Visible = false;
        GrdRewrite.Columns[3].Visible = GrdRewrite.Columns[5].Visible = GrdRewrite.Columns[6].Visible = true;
    }
    else if (Vanity.UrlPattern == Vanity.UrlType.ArticleOnly)
    {
        GrdRewrite.Columns[5].Visible = true;
        GrdRewrite.Columns[2].Visible = GrdRewrite.Columns[3].Visible = GrdRewrite.Columns[6].Visible = false;
    }
    else if (Vanity.UrlPattern == Vanity.UrlType.Normal)
    {
        GrdRewrite.Columns[2].Visible = true;
        GrdRewrite.Columns[3].Visible = GrdRewrite.Columns[5].Visible = GrdRewrite.Columns[6].Visible = false;
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    pnlAdmin.Visible = (objVanity.UserName == "host");

    if (objVanity.UserName == "host")
        Enable();
    else
        FieldsOpenForEditors(objVanity.SiteSupportUrlFormat);

    if (!IsPostBack)
    {
        Vanity.GenerateListFromEnums(drpAdminUrlType);
        if (objVanity.UserName == "host")
            Vanity.UrlPattern = Vanity.UrlType.ArticleOnly;
        else
            Vanity.UrlPattern = objVanity.SiteSupportUrlFormat;

        BindRewrite();
    }
}

任何人都可以告诉我如何在回发中保留枚举的价值

我认为viewstate可以是选项,但不知道如何存储枚举值并恢复枚举中输入的字符串值。

1 个答案:

答案 0 :(得分:7)

如果要在回发之间保留值,则需要将其存储在Session,Cache或ViewState中。

在您的情况下,ViewState可能是首选。

public UrlType UrlPattern
{
    get
    {
        if (ViewState["UrlPattern"] != null)
            return (UrlType)Enum.Parse(typeof(UrlType), ViewState["UrlPattern"].ToString());
        return UrlType.Normal; // Default value
    }
    set
    {
        ViewState["UrlPattern"] = value;
    }
}