验证模型解析 json 响应
我想知道是否有人可以向我指出一个教程,或者给我一个关于如何验证模型并通过解析客户端上的 json 响应来显示其错误消息的想法。我确信这一定已经被问过,但找不到问题。
0) 用户将必填字段留空。
1) 点击提交按钮。
2) 处理帖子并发出 ajax 请求。
3)action方法处理post,尝试将模型绑定到表单集合。检测错误,因为必填字段为空。
4) 返回一个 json 响应,传递它尝试绑定的对象模型。
5)我想知道如何解析 json 响应,这样如果我检测到任何错误(例如必填字段),我可以利用生成的数据标签并显示其相应的错误消息。
操作方法:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult ValidateTrade(FormCollection data) {
Trade addedGroup = new Trade ();
try {
UpdateModel(addedGroup);
}
catch (Exception ex) {
} return json(addedGroup);
}
Javascript:
$.ajax({
url: link,
type: "POST",
data: form.serialize(),
success: function (data) {
//Parse response so if I detect errors, like required field, make use of the data tags already generated by MVC, show the corresponding error message.
},
error: function (jqXhr, textStatus, errorThrown) {
},
complete: function () {
}
});
这是我的.cshtml:
@Html.LabelFor(model => model.Trade.Name)
@Html.TextBoxFor(model => model.Trade.Name)
@Html.ValidationMessageFor(model => model.Trade.Name)
生成的html:
<label for="Trade_Name">Name:</label>
<input class="input-validation-error" data-val="true" data-val-required="Name requiered." id="Trade_Name" name="Trade.Name" type="text" value="" />
<span class="field-validation-error" data-valmsg-for="Trade.Name" data-valmsg-replace="true">Name requiered.</span>
I’d like to know if someone could point me to a tutorial or give me an idea on how I should validate a model and display it's error messages by parsing a json response on the client. I am sure this must have been asked already but couldn't find the question.
0) User leaves empty required fields.
1) Hits submit button.
2) The post is handled and an ajax request is made instead.
3) The action method handles the post, tries to bind the model to the form collection. Detects errors as the required fields are empty.
4) Returns a json response, passing the object model it tried to bind.
5) I’d like to know how I could parse the json response so if I detect any errors, like a required field, I could make use of the generated data tags and display it's corresponding error message.
Action method:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult ValidateTrade(FormCollection data) {
Trade addedGroup = new Trade ();
try {
UpdateModel(addedGroup);
}
catch (Exception ex) {
} return json(addedGroup);
}
Javascript:
$.ajax({
url: link,
type: "POST",
data: form.serialize(),
success: function (data) {
//Parse response so if I detect errors, like required field, make use of the data tags already generated by MVC, show the corresponding error message.
},
error: function (jqXhr, textStatus, errorThrown) {
},
complete: function () {
}
});
Here’s my .cshtml:
@Html.LabelFor(model => model.Trade.Name)
@Html.TextBoxFor(model => model.Trade.Name)
@Html.ValidationMessageFor(model => model.Trade.Name)
Generated html:
<label for="Trade_Name">Name:</label>
<input class="input-validation-error" data-val="true" data-val-required="Name requiered." id="Trade_Name" name="Trade.Name" type="text" value="" />
<span class="field-validation-error" data-valmsg-for="Trade.Name" data-valmsg-replace="true">Name requiered.</span>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 jQuery Validate 插件。它允许您设置自定义规则。您可以指定 MVC 生成的类来使用插件的验证方法。
Check out the jQuery Validate plugin. It allows you to set custom rules. You can assign the MVC-generated classes to work with the plugin's validation methods.
MVC 有一个 RemoteValidator 标记,您可以添加其他属性以发送到服务器以进行验证,但这只会生成一条验证消息。
在某个时间点,我尝试按照您的建议进行操作,即通过 AJAX 向服务器发送数据,进行一些验证,返回错误列表,显示一些错误消息。我的做法是创建一个自定义对象,将其用于所有 JSON 响应。您可以扩展该对象以包含名称/值对的数组或列表,以便您识别哪些字段有错误。
这允许您将响应传回客户端并检查属性:
最大的问题是您必须在控制器内部编写验证,从而在控制器和视图之间创建依赖关系。我不喜欢那样。我的下一个项目使用 MVC 的内置客户端验证,按照 rauland 的建议使用 jQuery.Validate。如果设置正确,您可以使用一个操作通过检查 Request.IsAjaxRequest() 返回完整或部分视图,甚至返回 JSON 响应。还有很多工作要做,我发现内置验证是最容易使用的。
MVC has a RemoteValidator markup that you can add additional properties to send along to the server to do your validation but this only produces a single validation message.
At one point in time I tried to do what you are suggesting, that being sending data to the server via AJAX, doing some validation, returning a list of errors, display some error messages. How I did it was to create a custom object that I would use for all of my JSON responses. You could extend the object to include an array or List of name/value pairs that would allow you to identify which fields has errors.
This allows you to pass back a response to the client and check properties:
The biggest issue is that you would have to write the validation inside of the controllers creating a dependency between the Controllers and the Views. I didn't like that. My next project used the built in client validation for MVC that used jQuery.Validate as rauland suggested. If setup propertly you could use one action to either return a full or partial view or even a JSON response by checking Request.IsAjaxRequest(). There is much work to be done and I found that the build in validation was the easiest thing to use.