【发布时间】:2024-05-18 08:25:02
【问题描述】:
所以我发现了一个有趣的问题。 我有一个这样的模型:
public class ApplicantModel
{
[Display(Name = "Firstname", ResourceType = typeof(Resources))]
[MaxLength(50, ErrorMessageResourceName = "FirstName", ErrorMessageResourceType = typeof(Validations), ErrorMessage = null)]
[Required(ErrorMessageResourceName = "FirstName", ErrorMessageResourceType = typeof(Validations), ErrorMessage = null)]
public string Firstname { get; set; }
[Display(Name = "Surname", ResourceType = typeof(Resources))]
[MaxLength(50, ErrorMessageResourceName = "Surname", ErrorMessageResourceType = typeof(Validations), ErrorMessage = null)]
[Required(ErrorMessageResourceName = "Surname", ErrorMessageResourceType = typeof(Validations), ErrorMessage = null)]
public string Surname { get; set; }
}
这一切都很好,当我检查模型状态并且模型出现错误时,我会得到如下信息: 错误:
[{
Key = FirstApplicant.Firstname
Value = ["First name is required field"]
},
{
Key = FirstApplicant.Surname
Value = ["Surname name is required field"]
}].
这样也好。
编辑: 这是可视化为 JSON 对象的 c# ModelState 对象。实物是这样的:
ModelState
{System.Web.Mvc.ModelStateDictionary}
Count: 2
IsReadOnly: false
IsValid: false
Keys: Count = 2
Values: Count = 2
Results View: Expanding the Results View will enumerate the IEnumerable
但是我的问题是。是否有可能以某种方式更改密钥?我知道密钥是作为对象的名称创建的,然后是该对象的 name 属性。 所以这是有道理的,但是有什么办法可以改变这种默认行为吗?还是我必须更改对象的名称?
编辑2:
我在这里想要实现的是我有一个 c# ViewModel 和淘汰赛 ViewModel。当你进行服务器端验证时,你会得到我序列化并发送给客户端的这个键和值字典。 然后我在客户端调用这个函数:
var errors = @Html.Raw(Json.Encode(Model.Errors));
function showErrors(serializedErrors) {
var errors = JSON.parse(serializedErrors);
for (var i = 0; i < errors.length; i++) {
var error = errors[i];
var key = error.Key;
var property = eval("masterModel." + key);
property.setError(error.Value.ErrorMessage);
property.isModified(true);
}
}
showErrors(errors);
如果视图模型属性名称在服务器和客户端上匹配,这将正常工作。但例如在服务器端我有一个 FirstApplicant.FirstName,而在客户端它是 ApplicationOne.firstname。谢谢大家的帮助和cmets。我希望这次能更详细地解释我的问题。
【问题讨论】:
-
代码的哪一部分创建了这个 JSON 响应?
-
这不是 JSON 代码,抱歉,我应该多描述一下。它是 ModelState Keys/Values 对象。但将其可视化为 JSON 对象更容易。真实对象看起来像:ModelState {System.Web.Mvc.ModelStateDictionary} 计数:22 IsReadOnly:false IsValid:false 键:Count = 22 值:Count = 22 结果视图:展开结果视图将枚举 IEnumerable
-
您的意思是例如将“FirstApplicant.Firstname”更改为“Name”吗?
-
您的问题含糊不清。为什么你需要改变“钥匙”?
-
你想达到什么目的?
标签: asp.net-mvc data-annotations modelstate