开发者

Html.HiddenFor with enum

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 hidde开发者_如何学Gon 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?


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.


This is now supported out of the box in mvc5

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜