简体   繁体   English

MVC淘汰赛验证显示和

[英]MVC Knockout validation display and

I am using knockout for the first time and I am struggling to get my head around a problem. 我是第一次使用淘汰赛,我正在努力解决问题。

I have a page with multiple sections and want to be able to edit a section and submit to the controller, then display the saved details. 我有一个包含多个部分的页面,并且希望能够编辑一个部分并提交给控制器,然后显示已保存的详细信息。

Each section is a partial view which contains the display information and the form. 每个部分都是一个局部视图,其中包含显示信息和表格。 They are shown and hidden as required. 根据需要显示和隐藏它们。 I have the code working for submitting, but the problem is when the ModelState is not valid. 我有用于提交的代码,但是问题是当ModelState无效时。 I need to return to the form with the validation message displayed 我需要返回显示验证信息的表单

How can I display the form again when the server validation fails? 服务器验证失败时如何再次显示该表单? When the validation fails it currently goes back to the display section. 验证失败时,当前返回显示部分。

Also I have noticed the validation message does not display. 我也注意到验证消息没有显示。

I am sure this must be a common problem with a simple fix. 我敢肯定,使用简单的修复程序一定是一个普遍的问题。 I know there are knockout validation tools, but will need to do more complex business logic validation later on and need to get the technique working. 我知道有敲除验证工具,但以后需要进行更复杂的业务逻辑验证,并且需要使该技术起作用。

ViewModel: ViewModel:

    [Required]
    public DateTime? InterviewDate { get; set; }

View: 视图:

<div data-bind="if: showAdminInterviewDisplay" id="Display">
<div>
    <button data-bind="click: showInterviewForm" id="EditButton">Edit</button>
</div>
<div>
    @Html.Label("Inteview Date") :
    <label data-bind="text: interviewDate"></label>
</div>
</div>
<div data-bind="if: showAdminInterviewForm" id="Form">   
<div>
    @Html.Label("Interview Date")
    <input data-bind="value: interviewDate" id="interviewDatePicker" />
    @Html.ValidationMessageFor(m => m.InterviewDate)
</div>

<div>
    <button data-bind="click: saveInterviewDate">Submit</button> 
</div>

Knockout ViewModel: 剔除ViewModel:

function InterviewViewModel() {
    //Data
    var self = this;
    var jsonDate = @Html.Raw(Json.Encode(@Model.InterviewDate));
    var date = new Date(parseInt(jsonDate.substr(6)));

    self.interviewDate = ko.observable(dateFormat(date, "dd/mm/yyyy"));        
    self.showAdminInterviewDisplay = ko.observable(true);
    self.showAdminInterviewForm = ko.observable();

    self.showInterviewForm = function () {
        self.showAdminInterviewDisplay(false);
        self.showAdminInterviewForm(true);
        $("#interviewDatePicker").datepicker({dateFormat: 'dd/mm/yy'});
    };

    //Operations
    self.saveInterviewDate = function() {
        $.ajax("@Url.Action("SaveInterview")", {
            data: ko.toJSON(self),
            type: "post",
            contentType: "application/json",
            success: function(data) {
                self.showAdminInterviewDisplay(true);
                self.showAdminInterviewForm(false);
            }
        });
    };
};

ko.applyBindings(new InterviewViewModel());

Controller: 控制器:

      public ActionResult SaveInterview(KnockoutViewModel model)
    {
        if (ModelState.IsValid)
        {
            return Json(model);
        }
        return PartialView("_AdminInterview", model);
    }

Instead of returning a Partial View from your Action Method, return a serialised error model to the success function in the AJAX call. 与其从您的操作方法中返回部分视图,还不如将一个序列化的错误模型返回到AJAX调用中的成功函数。 The error model will contain all the errors in the ModelState. 错误模型将在ModelState中包含所有错误。

See this post on how to get and consume the errors from Model State: ASP.NET MVC How to convert ModelState errors to json (JK's answer) 有关如何从模型状态获取和使用错误的信息,请参见此文章: ASP.NET MVC如何将ModelState错误转换为json (JK的答案)

So you would have something like: 因此,您将获得以下内容:

Error Model: 错误模型:

public class JsonErrorModel
{
    public JsonErrorModel()
    {
        HasFailed = true;
    }

    public bool HasFailed { get; set; }
    public IEnumerable ErrorList { get; set; } 
}

Controller: 控制器:

if(ModelState.IsValid)
{    
  //Do whatever here 
  return Json(new { model });
}

return Json(new JsonErrorModel {ErrorList = ModelState.Errors()});

Success function of AJAX call: AJAX调用的成功功能:

 success: function (result) {                    
               if(result.HasFailed) {
                   self.showAdminInterviewDisplay(false);
                   self.showAdminInterviewForm(true);
                   DisplayErrors(result.ErrorList);
               }
               else {
                   self.showAdminInterviewDisplay(true);
                   self.showAdminInterviewForm(false);
               }
           }

So now, if the server side validation failed, the view will show the form and the validation errors. 因此,现在,如果服务器端验证失败,则该视图将显示表单和验证错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM