MVC3 HiddenFor with Enum. Input's value is enu

2019-07-16 03:27发布

问题:

I have an enum:

public enum TaskType
{
    None = 100,
    Install = 101,
    Decommission = 102,
    Modify = 103,
    Rename = 104,
    Move = 105,
    Incident = 106,
    Other = 107
};

and I would like to represent its current value in my view by saving it as a property of my model:

public class ProvisioningListModel
{
    public TaskType TaskType { get; set; }

    public ProvisioningListModel(Task task)
    {
        TaskType = task.TaskType;
    }
}

My view has the corresponding:

<%=Html.HiddenFor(model => model.TaskType)%>

When the appropriate hidden input element is generated, its value is "Install" and not "101." This seemed surprising to me because an enums are usually handled by their value not their key.

<input id="TaskType" name="TaskType" type="hidden" value="Install">

Is this a common issue in MVC? Is there an easy fix?

回答1:

first make your enum type to inherit from int

public enum TaskType :int
{
  ...

then simply use

<%=Html.HiddenFor(model => (int)model.TaskType)%>