开发者

Html.HiddenFor with enum

开发者 https://www.devze.com 2023-03-17 03:24 出处:网络
I have the following in my view: @Html.HiddenFor(x => x.MeasurementUnitType) MeasurementUnitType is an enum which looks like:

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

精彩评论

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