[英]Enum value instead of key in hidden HiddenFor field in Razor view (Asp.Net MVC 5)
I try to use this solution: 我尝试使用此解决方案:
MVC3 HiddenFor with Enum. MVC3 HiddenFor with Enum。 Input's value is enum key not value?
输入的值是枚举键而不是值?
However it does not work in MVC5 Razor view. 但是它在MVC5 Razor视图中不起作用。 I get this error:
我收到此错误:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code System.Web.Mvc.dll中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理
Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. 附加信息:模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。
How can I get enum value in hidden field instead of enum key? 如何在隐藏字段中获取枚举值而不是枚举键?
Enum type: 枚举类型:
public enum LineType : int
{
Account = 0,
Inventory = 1,
Service = 2
}
In Razor view I have: 在Razor视图中,我有:
@Html.HiddenFor(m => (int)m.LineTypeID)
LineTypeID is of type LineType. LineTypeID的类型为LineType。
You can do like 你可以这样做
@Html.HiddenFor(m => m.LineTypeID, new {@Value = (int)Model.LineTypeID})
This overrides key value 这会覆盖键值
Just to further detail the answer here: 只是为了进一步详细说明答案:
@Html.HiddenFor(m => (int)m.LineTypeID)
This will not work. 这不行。 You cannot cast on the template.
你不能在模板上施放。 When you cast it creates a new variable and this will not work.
当你施放它时会创建一个新变量,但这不起作用。
Remove the cast to int and add the @value field as described. 将转换移除到int并按所述添加@value字段。
@Html.HiddenFor(m => m.LineTypeID, new {@Value = (int)m.LineTypeID, id = "LineTypeID"})
I like to add the Id field so I can later easily access the value in JavaScript: 我想添加Id字段,以便以后可以轻松访问JavaScript中的值:
var lineTypeIDValue = parseInt($("#LineTypeID").val());
Also in C# you do not need to add a type to your enum. 同样在C#中,您不需要为枚举添加类型。
public enum LineType
{
Account = 0,
Inventory = 1,
Service = 2
}
You should now 你现在应该
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.