如何将 ModelState.AddModel Error 绑定到剔除动态创建的验证范围?

发布于 2025-01-01 15:58:51 字数 1632 浏览 1 评论 0原文

我已经设置 Knockoutjs 使用以下代码动态创建可编辑的值列表:

       var requirementModel = function() {
        var self = this;
        self.requirementtypes = ko.observableArray(@Html.Interpret(Model.requirementtypes));
        self.requirementid = ko.observable(@Html.Interpret(Model.requirementid));
        self.AddRequirementType = function() {
            self.requirementtypes.push({
                requirementtypeid: null,
                number: "",
                requirementid: 0
            });
        };
        self.RemoveType = function(Type) {
            self.requirementtypes.remove(Type);
        };
        self.hookUpValidation = function() {
            $.validator.unobtrusive.parseDynamicContent('.dynamicData');
        };
    };
    var viewModel = new requirementModel();
    ko.applyBindings(viewModel);

使用 html:

 <div class="small-box dynamicData"  data-bind="template:{ name: 'requirementType-template', foreach: requirementtypes, afterRender:$root.hookUpValidation }" ></div>
<button data-bind='click: AddType'>Add Type</button>

我已经使用 stackoverflow

当我回发到服务器时(我不使用 JSON 只是表单发布),我可以进行更复杂的验证,如果出现问题,我可以使用 ModelState.AddModelError("input field name", "I pity the folie that Break this" );对于非动态字段,这与强类型或 @Html.ValidationMessage("input field name") 完美配合

但是我找不到将服务器端模型错误挂钩到动态内容的方法。

我有与客户端配合使用的跨度标签,它们工作得很好。但是,它们不会与服务器端验证失败并返回页面后返回的数据挂钩。知道如何实现这一目标吗?

谢谢

I have setup Knockoutjs to dynamically create an editable list of values using the following code:

       var requirementModel = function() {
        var self = this;
        self.requirementtypes = ko.observableArray(@Html.Interpret(Model.requirementtypes));
        self.requirementid = ko.observable(@Html.Interpret(Model.requirementid));
        self.AddRequirementType = function() {
            self.requirementtypes.push({
                requirementtypeid: null,
                number: "",
                requirementid: 0
            });
        };
        self.RemoveType = function(Type) {
            self.requirementtypes.remove(Type);
        };
        self.hookUpValidation = function() {
            $.validator.unobtrusive.parseDynamicContent('.dynamicData');
        };
    };
    var viewModel = new requirementModel();
    ko.applyBindings(viewModel);

With html:

 <div class="small-box dynamicData"  data-bind="template:{ name: 'requirementType-template', foreach: requirementtypes, afterRender:$root.hookUpValidation }" ></div>
<button data-bind='click: AddType'>Add Type</button>

I have hooked up validation for dynamic data using the code recommended on stackoverflow.

When I post back to the server (I'm not using JSON just form post) I can do more complex validation and if something fails I can use ModelState.AddModelError("input field name", "I pity the fool that broke this"); This works perfectly with either strongly type or @Html.ValidationMessage("input field name") for non dynamic fields

However I can't find a way to hook Server Side Model Error to dynamic content.

I have the span tags that work with the client side and they work perfectly. However they aren't getting hooked into data returned after serverside validation fails and return page. Any idea how to acheive this?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

征﹌骨岁月お 2025-01-08 15:58:51

我刚刚完成了我当前工作项目的编码。我无法发布调解规则的代码。就像您上面的评论所说,没有一种优雅的方式。我将描述我们显示错误消息所采取的步骤。

首先,修改动态生成的 html,以便每个 html 都具有与 MVC3 @Html.ValidationFor(...) 控件等效的代码。接下来,每个动态控件都需要有一个 id 字段,您可以使用该字段来定位要添加错误消息的控件。

我采取的步骤是,在控制器接收到要验证的ajax数据后开始 -

  1. 验证接收到的数据模型

  2. 创建一个类以返回如下所示的结果

    类 AjaxResults{
        布尔成功{得到;放;);
        对象返回数据{get;放;);
    }
    
  3. 如果模型验证,则返回 AjaxResults,其中 success = true 和 returnedData = "验证数据模型"

  4. 如果模型未验证,则

  5. 所有错误收集到一个对列表中。其中 key = fieldID,value =“错误消息”。
  6. 返回 AjaxResultssuccess = false 且 returnedData =“错误列表”

  7. 客户端收到 AjaxResults 对象后

  8. 如果success = true,则正常处理结果。

  9. 如果 success = false,则循环访问列表,突出显示有错误的字段并显示错误消息。

在最后一步中,您可以使用 jquery 验证消息显示错误代码。如果您想执行此操作,请在 jquery.unobtrusive.valiation.js 文件中

  1. 添加代码以复制文件中 onError 方法的功能。
  2. 添加代码以通过错误列表进行交互,调用 onError 方法来显示消息。请注意,信息存储在错误消息范围的 .data 属性中。
  3. 您可能需要编写代码来在提交表单时清除所有这些错误。

这是一个相当长的过程。但代码很容易模块化为可调用的例程。我们目前正在我们的生产代码中使用它,并且在实践中,它成为我们框架代码的一部分。

希望这有帮助。

I've just finished coding this for my current work project. I cannot post the code for propitiatory rules. Like your comment above says, there isn't an elegant way. I will describe the steps that we took to display our error messages.

First, modify your dynamically generated html so that each has the equivalent code to MVC3 @Html.ValidationFor(...) control. Next each dynamic control needs to have an id field that you can use to locate control to add error message to.

Steps I took were, starting after the controller receives the ajax data for validation -

  1. Validate the received data model

  2. Create a class to return the results that looks like this

    Class AjaxResults{
        bool success {get; set;);
        object returnedData {get; set;);
    }
    
  3. If model validates, return AjaxResults with success = true and returnedData = "validated data model"

  4. If models does not validate then

  5. Collect all the errors into a list of pairs. Where key = fieldID and value = "the error message".
  6. return AjaxResults with success = false and returnedData = "list of errors"

  7. After client receives the AjaxResults object

  8. If success = true, process result normally.

  9. If success = false, iterate through list highlighting the fields with the error and displaying the error message.

In the last step, you can use the jquery validation message display the error code. If you want to do this, then in jquery.unobtrusive.valiation.js file

  1. Add code to duplicate the functionality of onError method in the file.
  2. Add code to interate through the error list calling your onError method to display the messages. Be careful here in that information is stored in the .data attribute of the Error Message span.
  3. You may need to write code to clear all of these errors upon submitting the form.

This is a fairly long procedure. But the code is easily modularized into callable routines. We are currently using this in our production code and in practice, it becomes part of our framework code.

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文