剔除模板绑定中的不显眼的客户端验证
我有一个带有数据注释的模型,并且我是一个使用淘汰模板绑定和映射插件与视图模型动态绑定的模型。我正在尝试对我的模型进行不显眼的客户端验证。在这种情况下我们如何做到这一点。有什么帮助/建议吗?
public class MyUser
{
[Required]
[StringLength(35)]
public string Username { get; set; }
[Required]
[StringLength(35)]
public string Forename { get; set; }
[Required]
[StringLength(35)]
public string Surname { get; set; }
}
在我看来,我正在使用 ajax 动态模板绑定 MyUser 列表。
public JsonResult TestKnockout()
{
IList<MyUser> myUserList = new List<MyUser>();
myUserList.Add(new MyUser { Username = "ajohn", Surname = "surname" });
myUserList.Add(new MyUser { Username = "ajohn1", Surname = "surname1" });
return Json(myUserList, JsonRequestBehavior.AllowGet);
}
}
看法:
<form id="Userform" action='@Url.Action("Save", "Home")' data-bind="template: {name: 'UserTemplate', foreach:UserList}">
<input type="Submit" name="name" value="Submit" />
</form>
<script id="UserTemplate" type="text/Html">
<input type="text" data-bind="value: Username"></input>
<input type="text" data-bind="value: Forename"></input>
<input type="text" data-bind="value: Surname"></input>
</script>
<script type="text/javascript">
var viewModel = {
UserList: ko.observableArray(new Array()),
Save: function () {
//// reached here means validation is done.
alert("Save");
}
}
ko.applyBindings(viewModel);
$.ajax({
type: 'GET',
url: '../Home/TestKnockout',
contentType: "application/json",
success: function (data) {
$.each(ko.mapping.fromJS(data)(), function () {
viewModel.UserList.push(this);
})
// attach the jquery unobtrusive validator
$.validator.unobtrusive.parse("#Userform");
// bind the submit handler to unobtrusive validation.
$("#Userform").data("validator").settings.submitHandler = viewModel.Save;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
</script>
I have a model with data annotations and i am an dynamically binding that with viewmodel using knockout template binding and mapping plugin. I am trying to do a unobtrusive client validation to be done on my model. How we can do that in this scenario. Any help/suggestions?
public class MyUser
{
[Required]
[StringLength(35)]
public string Username { get; set; }
[Required]
[StringLength(35)]
public string Forename { get; set; }
[Required]
[StringLength(35)]
public string Surname { get; set; }
}
In my view i am dynamically template binding a list of MyUser using ajax.
public JsonResult TestKnockout()
{
IList<MyUser> myUserList = new List<MyUser>();
myUserList.Add(new MyUser { Username = "ajohn", Surname = "surname" });
myUserList.Add(new MyUser { Username = "ajohn1", Surname = "surname1" });
return Json(myUserList, JsonRequestBehavior.AllowGet);
}
}
View:
<form id="Userform" action='@Url.Action("Save", "Home")' data-bind="template: {name: 'UserTemplate', foreach:UserList}">
<input type="Submit" name="name" value="Submit" />
</form>
<script id="UserTemplate" type="text/Html">
<input type="text" data-bind="value: Username"></input>
<input type="text" data-bind="value: Forename"></input>
<input type="text" data-bind="value: Surname"></input>
</script>
<script type="text/javascript">
var viewModel = {
UserList: ko.observableArray(new Array()),
Save: function () {
//// reached here means validation is done.
alert("Save");
}
}
ko.applyBindings(viewModel);
$.ajax({
type: 'GET',
url: '../Home/TestKnockout',
contentType: "application/json",
success: function (data) {
$.each(ko.mapping.fromJS(data)(), function () {
viewModel.UserList.push(this);
})
// attach the jquery unobtrusive validator
$.validator.unobtrusive.parse("#Userform");
// bind the submit handler to unobtrusive validation.
$("#Userform").data("validator").settings.submitHandler = viewModel.Save;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
pilavdzice 和 drogon 的答案相当好,但我们忘记了基本点。
由于我们使用 MVVM 模式来分离 UI 和数据 (+vm),因此我们不想执行 UI 验证,而是执行数据验证。这两个是完全不同的,jquery validate 是一个很棒的插件,但它执行 UI 验证(它从 UI 开始检查字段)。
我发现 knockout 验证插件 它似乎做得很好,它所做的是走相反的路,它验证你的viewmodel 而不是您的 UI(它实际上映射到 UI 元素以显示错误)。
不幸的是,如果您的视图模型变得复杂,该插件将会出现一些问题,但无论如何这都是要走的路。
只要我们不使用 MVVM 模式,UI 验证就是完美的,毕竟我们分离组件 (MV-VM) 的目的是什么?
希望我有帮助!
谢谢!
pilavdzice and drogon answers are quite good but we forget the basic point.
Since we are using an MVVM pattern for the seperation of UI and data (+vm) we don't want to perform UI validation but DATA VALIDATION. Those two are quite different, jquery validate is a great plugin but it does UI validation (it starts from UI to check the fields).
I have found knockout validation plugin which seems to do quite well and what it does is to go the opposite road, it validates your viewmodel and not your UI (it actually maps to UI elements to display the errors).
Unfortunately If your viewmodel gets complex, that plugin will have some problems, but in any case this is the way to go.
UI validation is perfect as long as we are not using an MVVM pattern, after all what do we separate the components (M-V-VM) for ?
Hope I helped !
Thanks!
我遇到了和你一样的问题,所以我编写了以下组件。
https://www.nuget.org/packages/ScriptAnnotations/
https://scriptannotations.codeplex.com/
如果这有帮助,请告诉我。
I had the same problem as you so I wrote the following component.
https://www.nuget.org/packages/ScriptAnnotations/
https://scriptannotations.codeplex.com/
Please let me know if this helps.
我会使用 jquery 的事件绑定来实现这一点。
首先,将 data-val 属性添加到要验证的输入中。 (为了确定要使用哪些 data-val 属性,我通常将表单服务器端绑定到模型和视图源。)
其次,添加一个验证实用函数——这会调用 MVC 在幕后使用的 jquery 验证插件。
第三,在发出视图模型方法之前调用验证。确保从页面标记中删除“点击”数据绑定属性。
I would go with jquery's event binding for this.
First, add your data-val attributes to the inputs you want to validate. (To figure out which data-val attributes to use, I usually bind a form server-side to a model and view source.)
Second, add a validation utility function --this calls the jquery validation plugin used by MVC under the covers.
Third, call validate before issuing your viewmodel method. Make sure to remove the "click" data-bind attribute from the markup in your page.
如果您使用knockoutjs 和jquery,我想出了以下非常简单的方法来进行基本验证。
无论您想在页面上的何处显示错误消息,请包含一个如下所示的跨度标记:
显然,您需要编写“yourValidationFunction”来执行您希望它执行的任何操作。它只需要返回 true 或 false,true 表示显示错误。
如果显示任何验证错误,您可以使用 jquery 阻止用户继续操作。您可能已经有一个保存按钮,可以触发 javascript 函数来执行一些 ajax 或其他操作,因此只需将其包含在其顶部即可:
这比许多其他验证解决方案更简单、更灵活。您可以将错误消息放置在任何您想要的位置,并且不需要学习如何使用某些验证库。
If you are using knockoutjs and jquery, I came up with the following very simple method for doing basic validation.
Wherever you want to display the error message on your page, include a span tag like this:
Obviously you need to write "yourValidationFunction" to do whatever you want it to do. It just needs to return true or false, true means display the error.
You can use jquery to prevent a user from proceeding if any validations errors are displayed. You probably already have a save button that triggers a javascript function to do some ajax or whatever, so just include this at the top of it:
This is a lot simpler and more flexible than many other validation solutions out there. You can position your error message wherever you want, and you don't need to learn how to use some validation library.