Html.HiddenFor with enum

2019-04-13 10:04发布

问题:

I have the following in my view:

@Html.HiddenFor(x => x.MeasurementUnitType)

MeasurementUnitType is an enum which looks like:

public enum MeasurementUnitType
{
    Metric, Imperial
}

Whatever happens to that enum on the model, the hidden field is always set to metric.

I did try having an editor template for it:

@using Ns.Domain.Models.Enums
@model Ns.Domain.Models.Enums.MeasurementUnitType
@{
    switch (Model)
    {
        case MeasurementUnitType.Metric:
    <text>
    @Html.Hidden("Metric", ViewData.TemplateInfo.FormattedModelValue)
    </text>
break;
        case MeasurementUnitType.Imperial:
    <text>
    @Html.Hidden("Imperial", ViewData.TemplateInfo.FormattedModelValue)
    </text>
break;
        default:
throw new ArgumentOutOfRangeException();
    }
}

but that would output the hidden field as

 <input id="NewTable_MeasurementUnitType_Metric" name="NewTable.MeasurementUnitType.Metric" type="hidden" value="Metric" />

or

 <input id="NewTable_MeasurementUnitType_Imperial" name="NewTable.MeasurementUnitType.Metric" type="hidden" value="Imperial" />

respectively

this wont work as the Id has the actual value of the enum as well as the name of the enum in the Id...

Anyone got any ideas?

回答1:

Try doing it like this:

   @Html.Hidden(ViewData.ModelMetadata.PropertyName, 
     ViewData.TemplateInfo.FormattedModelValue)

You might then also be able to get away with no switch statement.

You might also have fallen foul of the apparent MVC bug (which isn't), mentioned on another SO, whereby MVC will use ValueProvider-provided values from a POST request if you re-render the view.



回答2:

This is now supported out of the box in mvc5

https://aspnet.codeplex.com/SourceControl/latest#Samples/MVC/EnumSample/