将非字段相关错误添加到 asp mvc 表单
我在 ASP MVC 错误处理方面遇到了一些麻烦。
在用户尝试连接到设备的表单上。如果用户输入无效的设备名称,则可以非常简单地告诉用户该名称无效。
我正在实施 IEnumerable
。 RuleViolation
类有两个字段:PropertyName
和 ErrorMessage
,如果我在提交时收到错误,我只需调用 GetRulesViolations 方法并将错误设置为ModelState:
catch {
foreach (var issue in device.GetRulesViolations()) {
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
return View();
}
并且使用一些背景 asp mvc 魔法,错误出现在模型的 ValidationMessage 占位符的视图上。名称:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Connect" />
</p>
</fieldset>
}
现在的问题:
如果我收到的错误类似于“无法连接到设备”这不是与 Name
字段相关的问题。该消息应该出现在表单上方,因为它与整个表单相关。
有没有一种简单的方法可以像 ModelState.AddError("error message") 一样设置它而不告诉键,以便它适用于整个表单,或者我应该在 Data 类上创建一个 Error
隐藏属性并在表单上方放置该属性的验证消息?
I'm having some troubles with ASP MVC error handling.
On a form that a user tries to connect to a device. If the uses input an invalid device name, it's pretty straightforward to tell the user the name is invalid.
I'm implementing IEnumerable<RuleViolation> GetRulesViolations()
on all my data classes. The RuleViolation
class has two fields: PropertyName
and ErrorMessage
and if I get an error on submit I just call the GetRulesViolations method and set the errors on the ModelState:
catch {
foreach (var issue in device.GetRulesViolations()) {
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
return View();
}
and with some background asp mvc magic the error appears on the view in the ValidationMessage placeholder for the model.Name:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Connect" />
</p>
</fieldset>
}
Now the problem:
If the error i'm getting is something like "Could not connect to the device" that's not a problem related to the Name
field. It's a message that should appear above the form because it's related to the whole form.
Is there a straightforward way to set this like ModelState.AddError("error message") without telling the key so it would apply to the whole form or should I create an Error
hidden property on the Data classes and place a validation message for that property above the form?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,空字段名称,如下所示:
Yes, empty field name, like this :