Knockoutjs code to work after controller returns

1

I have an application that uses Knockoutjs, but when saved it returns some error the button that uses Knockutjs to and does not work, only after refreshing the page does it work properly, does anyone know what it can be.

csHtml

@model Entities.InternalAuditRecord
@using Entities
@using UI.Models
@using UI.Extensions
@using UI.HtmlHelpers
@{
    ViewBag.Title = "Registro de Auditoria Interna";
    Layout = IsAjax ? null : "~/Views/Shared/_Master.cshtml";
    var canWrite = User.CanWrite(AuditingPath.InternalAuditRecord);
}

@section scripts{

    <script type="text/html" id="internalAuditRecordTopicTemplate">
        <section class="internalAuditRecordTopicDetail with-margin" data-index="${$index}">
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].Request" value="${Request}" />
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].Name" value="${Name}" />
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].Comformity" value="${Comformity}" />
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].NonComformityType" value="${NonComformityType}" />
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].OM" value="${OM}" />
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].Observation" value="${Observation}" />
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].Evidences" value="${Evidences}" />
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].InternalAuditRecordID" value="${InternalAuditRecordID}" />
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].InternalAuditRecordTopicID" value="${InternalAuditRecordTopicID}" />
            <input type="hidden" name="InternalAuditRecordTopics[${$index}].Order" value="${$index}" />
            <fieldset class="grey-bg relative internalAuditRecordTopic">
                <ul class="mini-menu visible">
                    {{if $parent.InternalAuditRecordTopics().length > 1 }}
                    {{if $index() > 0}}
                    <li>@Html.UpIcon(null, new { data_bind = "click: $parent.upInternalAuditRecordTopic", @Title = "Subir Item" })</li>
                    {{/if}}
                    {{if $index() < $parent.InternalAuditRecordTopics().length - 1}}
                    <li>@Html.DownIcon(null, new { data_bind = "click: $parent.downInternalAuditRecordTopic", @Title = "Descer Item" })</li>
                    {{/if}}
                    {{/if}}
                    <li>@Html.DeleteIcon(null, new { @Title = "Remover Item", data_bind = "click: $parent.removeInternalAuditRecordTopic" })</li>
                </ul>
                <legend>
                    @*<a href="#" data-bind="text: Name"></a>*@
                    <span>
                        <input type="text" style="width:300px;" class="internalAuditRecordTopicRequest" placeholder="Requisito" data-bind="value:Request" /> 
                    </span>
                </legend>
                <table class="tg">
                    <tr>
                        <td class="tg-yw4l" align="right"><span class="label" style="color:black">Registros da Auditoria: </span></td>
                        <td><textarea cols="65" rows="10" style="width:400px;" class="internalAuditRecordTopicName" placeholder="Nome do tópico" data-bind="value:Name" /></td>
                    </tr>
                    <tr>
                        <td  class="tg-yw4l" align="right"><span class="label" style="color:black">Não Conformidade: </span></td>
                        <td  class="tg-yw4l"><span id="span_finished">
                                <select data-bind="value: NonComformityType">
                                    <option value="" disabled selected>Escolher</option>
                                    <option value="2">Maior</option>
                                    <option value="1">Menor</option>
                                </select>
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td class="tg-yw4l" align="right"><span for="active" class="label" style="color:black">OM: </span></td>
                         <td><span><input type="checkbox" value="1" data-bind="checked:OM" class="float-left" /></span></td>
                    </tr>
                    <tr>
                        <td class="tg-yw4l" align="right"><span class="label" style="color:black">Observações: </span></td>
                        <td><textarea cols="65" rows="10" style="width:400px;" class="internalAuditRecordTopicName" placeholder="Observações" data-bind="value:Observation" /></td>
                    </tr>
                    <tr>
                        <td class="tg-yw4l" align="right"><span for="active" class="label" style="color:black">Comforme? </span></td>
                        <td><input type="checkbox" value="1" data-bind="checked:Comformity" class="float-left" /></td>
                    </tr>
                    <tr>
                        <td class="tg-yw4l" align="right"><span class="label" style="color:black">Evidências: </span></td>
                        <td><textarea cols="65" rows="10" style="width:400px;" class="internalAuditRecordTopicName" placeholder="Evidências" data-bind="value:Evidences" /></td>
                    </tr>
                </table>

           </fieldset>
        </section>
        <hr />
    </script>


    <script>

        var InternalAuditRecordTopic = function (data) {
            var self = this;
            self.InternalAuditRecordTopicID = ko.observable(data.InternalAuditRecordTopicID);
            self.InternalAuditRecordID = ko.observable(data.InternalAuditRecordID);
            self.Name = ko.observable(data.Name);
            self.Order = ko.observable(data.Order);
            self.Request = ko.observable(data.Request);
            self.NonComformityType = ko.observable(data.NonComformityType);
            self.Comformity = ko.observable(data.Comformity);
            self.OM = ko.observable(data.OM);
            self.Observation = ko.observable(data.Observation);
            self.Evidences = ko.observable(data.Evidences);

            self.startPlaceHolders = function () {
                startPlaceHolders();
            };

        };

        var InternalAuditRecordTopicEmpty = {
            InternalAuditRecordTopicID: 0,
            InternalAuditRecordID: 0,
            Name:'',
            Order:9999,
            Request:'',
            NonComformityType:'',
            Comformity:'',
            OM:'',
            Observation:'',
            Evidences:'',
        };


        var InternalAuditRecord = function (data) {
            var self = this;
            self.InternalAuditRecordID = ko.observable(data.InternalAuditRecordID);
            self.Active = ko.observable(data.Active);
            self.Name = ko.observable(data.Name);
            self.InternalAuditRecordTopics = ko.observableArray();
            if (typeof (data.InternalAuditRecordTopics) == "object" && data.InternalAuditRecordTopics != null) {
                $.each(data.InternalAuditRecordTopics, function (index, value) {
                    self.InternalAuditRecordTopics.push(new InternalAuditRecordTopic(value));
                });
            }

            self.startPlaceHolders = function () {
                startPlaceHolders();
            };

            self.AddInternalAuditRecordTopic = function (a, event) {
                var lastOrderInternalAuditRecordTopic = self.InternalAuditRecordTopics().length - 1;
                var newInternalAuditRecordTopic = InternalAuditRecordTopicEmpty;
                newInternalAuditRecordTopic.Order = lastOrderInternalAuditRecordTopic;
                self.InternalAuditRecordTopics.push(new InternalAuditRecordTopic(newInternalAuditRecordTopic));
                startPlaceHolders();
            };

            self.InternalAuditRecordTopics.sort(function (a, b) {
                return (a.Order() > b.Order()) ? 1 : -1;
            });

            self.downInternalAuditRecordTopic = function (a, event) {
                var index = self.InternalAuditRecordTopics.indexOf(a);
                if (index < self.InternalAuditRecordTopics().length - 1) {
                    $(event.target).parent().hideTip();
                    var removed = self.InternalAuditRecordTopics.splice(index, 1);
                    removed = ko.toJS(removed)[0];
                    self.InternalAuditRecordTopics.splice(index + 1, 0, new InternalAuditRecordTopic(removed));
                }
            }

            self.upInternalAuditRecordTopic = function (a, event) {
                var index = self.InternalAuditRecordTopics.indexOf(a);
                if (index >= 1) {
                    $(event.target).parent().hideTip();
                    var removed = self.InternalAuditRecordTopics.splice(index, 1);
                    removed = ko.toJS(removed)[0];
                    self.InternalAuditRecordTopics.splice(index - 1, 0, new InternalAuditRecordTopic(removed));
                }
            }

            self.removeInternalAuditRecordTopic = function (a, event) {
                var index = self.InternalAuditRecordTopics.indexOf(a);
                $(event.target).parent().hideTip();
                self.InternalAuditRecordTopics.splice(index, 1);
            }

            self.editInternalAuditRecordTopic = function (a, event) {
                var index = self.InternalAuditRecordTopics.indexOf(a);
                $(event.target).parent().hideTip();
                internalAuditRecordTopicForm(index, a.Name());
            }
        };

        ko.cleanNode($("form#internalAuditRecordRegisterForm"));
        var viewModel = new InternalAuditRecord(@Html.Raw(Model.ToJson()));
        ko.applyBindings(viewModel, document.getElementById("internalAuditRecordRegisterForm"));

        function internalAuditRecordTopicForm() {
            var internalAuditRecordIdx = arguments[0] || -1;
            var name = arguments[1] || '';
            var internalAuditRecordID = $("#internalAuditRecordRegisterForm #InternalAuditRecordID:first").val();
            var data = {
                InternalAuditRecordID: internalAuditRecordID,
                Order: internalAuditRecordIdx,
                Name: name,
            }

            $.ajax({
                type: 'post',
                url: "/Exam/InternalAuditRecordTopicForm",
                type: 'post',
                cache: false,
                data: data,
                success: function (res) {
                    $.modal({
                        title: "Cadastro de Item de InternalAuditRecordTopicEntryário",
                        content: res,
                    });
                }
            });
        }

        function attachInternalAuditRecordTopic(obj) {
            if (obj.Order == -1)
                viewModel.InternalAuditRecordTopics.push(new InternalAuditRecordTopic(obj));
            else
                viewModel.InternalAuditRecordTopics()[obj.Order].Name(obj.Name);
            $(".internalAuditRecordTopicDetail").applyTemplateSetup();
        }

        function saveInternalAuditRecordTopic() {
            var itemName = $("#internalAuditRecordTopicRegisterForm #Name").val();
            var idx = $("#internalAuditRecordTopicRegisterForm #Order").val();
            var internalAuditRecordID = viewModel.InternalAuditRecordID();

            var data = {
                InternalAuditRecordID: internalAuditRecordID,
                Name: itemName,
                Order: idx,
            }

            $.ajax({
                type: 'post',
                url: '/Exam/SaveInternalAuditRecordTopic',
                data: data,
                cache: false,
                async: false,
                success: function (res) {
                    if (typeof (res) == "object") { //success
                        attachInternalAuditRecordTopic(res.detail);
                        $.modal.current.closeModal();
                    }
                    else { //fail
                        $.modal.current.setModalContent(res, true);
                    }
                }
            });
        }

        function validationFields() {

            //Namne
            if ($("#Name").val() == "") {
               $("#Name").addClass(validationClassErrosType.input)
            }
            validationCheckImage($("#Name"), $("#Name").parent());


            $(".internalAuditRecordTopic").each(function () {
                var internalAuditRecordTopicName = $(this).find(".internalAuditRecordTopicName");
                if (internalAuditRecordTopicName.val() == "") {
                    internalAuditRecordTopicName.addClass(validationClassErrosType.input);
                }
                validationCheckImage(internalAuditRecordTopicName, internalAuditRecordTopicName.parent());
            });
        }

        function saveInternalAuditRecord() {
            removeAllPlaceHolder();
            clearErrorsMessages();
            responsibles = "";
            $("select#Responsibles option").each(function () {
                responsibles += $(this).val() + ",";
            });
            auditors = "";
            $("select#Auditors option").each(function () {
                auditors += $(this).val() + ",";
            });
            $.ajax({
                url: "/InternalAuditRecord/SaveInternalAuditRecord",
                type: "post",
                data: $("form#internalAuditRecordRegisterForm").serialize()+"&idResponsibles="+responsibles+"&idAuditors="+auditors,
                success: function (res) {
                    if (typeof (res) == "object") {
                        if (res.success) {
                            window.location.replace("/InternalAuditRecord/InternalAuditRecord");
                        }
                        else {
                            flashMessage();
                        }
                    }
                    else {
                        $("article.container_12").replaceWith(res);

                        validationCheckImage("#Name", "#span_location");
                        //$("#Name").addClass("input-validation-error");

                        loadSwitches();
                        $('html, body').animate({ scrollTop: 0 }, 'fast');
                    }
                }, error: function () {
                    $("#messages").html("<p class=\"message error no-margin\" style=\"margin-bottom:10px !important;\">Ocorreu um erro durante a gravação dos dados.</p>");
                }

            });
        }

        function cancelInternalAuditRecord() {
            window.history.back()
        }

        $(document).ready(function () {
            $("#addInternalAuditRecordTopic").live("click", function () {
                saveInternalAuditRecordTopic();
            });

            $("#saveInternalAuditRecord").live("click", function () {
                saveInternalAuditRecord();
            });

            $("#cancelInternalAuditRecord").live("click", function () {
                cancelInternalAuditRecord();
            });

            $(".addOption").live("click", function () {
            });

            $(".cancelOption").on("click", function () {
                cancelChangesOption($(this));
            })

            $("#closeModal").live("click", function () {
                $.modal.current.closeModal();
            });
        });
    </script>
}


@Scripts.Render("~/bundles/internalAuditRecordForm")

<article class="container_12">
    <section class="grid-12">
        <div class="block-border">
            <div class="block-content clearfix" id="supplierFormDiv">
                <h1>Cadastro Auditoria Interna</h1>
                @if (Model.Detail)
                {
                    <script type="text/javascript">
                        $(function () {
                            $('input, select, textarea').attr('disabled', 'disabled');
                        });
                    </script>
                }
                <form class="form" id="internalAuditRecordRegisterForm" style="width: 750px; margin-left: auto; margin-right: auto;" enctype="multipart/form-data">
                    @Html.HiddenFor(m => m.InternalAuditRecordID)
                    <fieldset>
                        <div id="messages">@Html.ValidationSummary()</div>
                        <div class="field-wrap inline-label">  
                            <label for="" style="text-align:right;">Data da Auditoria: </label>
                            <span id="span_auditdate" class="input-type-text">
                                @Html.TextBoxFor(s => s.AuditDate, new { @class = "hasDatePick" }).Enable(canWrite)
                                @if (canWrite)
                                {
                                    @Html.CalendarIcon("#", new { id = "AuditDateIcon" })
                                }
                            </span>
                            <div id="datepickTargetExperience"></div>
                        </div>
                        <div class="field-wrap inline-label">
                            <label for="" style="text-align:right;">Descrição: </label>
                            <span id="span_location" @*class="input-type-text"*@>
                                @Html.TextBoxFor(s => s.Name, new { placeholder = "Descrição", maxlength = "256"}).Enable(canWrite)
                            </span>
                        </div>
                        <div class="field-wrap inline-label">
                            <label for="" style="text-align:right;">Processo: </label>
                            <span id="span_location" class="input-type-text">
                                @Html.TextBoxFor(s => s.Process, new { placeholder = "Processo", maxlength = "256" }).Enable(canWrite)
                            </span>
                        </div>

                        <div class="field-wrap inline-label clearfix">
                            <label for="AbsentID" style="text-align:right;">Auditores: </label>
                            <span id="span_sectors">
                                @Html.DropDownListFor(e => e.Auditors, ((IEnumerable<SelectListItem>)ViewData["auditorsSelection"]), new { multiple = "multiple", @class = "float-left multiple-drop-down" }).Enable(canWrite)
                            </span>
                            @if (canWrite)
                            {
                                @Html.AddIcon("#", new { onclick = "addAuditors(); return false;", @Style = "margin: 0 10px 0 5px;" })
                                @Html.RemoveIcon("#", new { onclick = "removeAuditors(); return false;" })
                            }
                        </div>

                        <div class="field-wrap inline-label clearfix">
                            <label for="AbsentID" style="text-align:right;">Responsáveis: </label>
                            <span id="span_sectors">
                                @Html.DropDownListFor(e => e.Responsibles, ((IEnumerable<SelectListItem>)ViewData["responsiblesSelection"]), new { multiple = "multiple", @class = "float-left multiple-drop-down" }).Enable(canWrite)
                            </span>
                            @if (canWrite)
                            {
                                @Html.AddIcon("#", new { onclick = "addResponsibles(); return false;", @Style = "margin: 0 10px 0 5px;" })
                                @Html.RemoveIcon("#", new { onclick = "removeResponsibles(); return false;" })
                            }
                        </div>

                        <div id="internalAuditRecordTopicsPanel" class="with-margin" data-bind="visible: InternalAuditRecordTopics().length > 0">
                            <hr />
                            <div data-bind="template: { name: 'internalAuditRecordTopicTemplate', foreach: InternalAuditRecordTopics, afterRender: startPlaceHolders }"></div>
                        </div>

                        <button type="button" data-bind="click: AddInternalAuditRecordTopic" style="cursor: pointer;">Novo Tópico</button>
                    </fieldset>
                    <div class="float-right">
                        @if (Model.Detail == false)
                        {
                            @Html.Button("Salvar", canWrite, new { type = "submit", onclick = "saveInternalAuditRecord();" })
                        }
                        @Html.Button("Cancelar", new { @class = "red", onClick = "cancelInternalAuditRecord()" })
                    </div>
                </form>
            </div>
        </div>
    </section>

</article>
<script type="text/javascript">
    $(document).ready(function () {
        $("#Process").click(function (event) {
            event.preventDefault();
            title = "Processo";
            element = $("input#ProcessID");
            textbox = $("input#Process");
            var title, element, textbox;

            var modal = $(this).getModalWindow();

            $.ajax({
                url: "/Process/ProcessSelection",
                datatype: "html",
                success: function (data) {
                    modal.hide();
                    $.modal({
                        content: data,
                        title: title,
                        maxHeight: 480,
                        width: 660,
                        buttons: {
                            "Selecionar": function (wind) {
                                selectUser(element, textbox);
                                modal.show();
                                wind.closeModal();
                            },
                            "Cancelar_red": function (wind) { modal.show(); wind.closeModal(); }
                        },
                        onClose: function () {
                            modal.show();
                        }
                    });
                },
                error: function () {
                    alert("Não foi possível completar a requisição");
                }
            });

        });          

    }

);
    function selectUser(element, textbox) {
        var idUser = $("input[name='inputName']:checked").val();
        var name = $("input[name='inputName']:checked").attr("data-text");
        element.val(idUser);
        textbox.val(name);
    }


</script>

Controller

public ActionResult SaveInternalAuditRecord(InternalAuditRecord criticalAnalysisRecord, string idResponsibles, string idAuditors)
        {


            SetViewData(idResponsibles, idAuditors);

            List<User> usersSelectionList = new List<User>();
            if (!string.IsNullOrWhiteSpace(idResponsibles)) usersSelectionList = idResponsibles.TrimEnd(',').Split(',').Select(x => userRepository.GetById(int.Parse(x))).ToList();
            foreach (User user in usersSelectionList) criticalAnalysisRecord.Responsibles.Add(user);

            usersSelectionList = new List<User>();
            if (!string.IsNullOrWhiteSpace(idAuditors)) usersSelectionList = idAuditors.TrimEnd(',').Split(',').Select(x => userRepository.GetById(int.Parse(x))).ToList();
            foreach (User user in usersSelectionList) criticalAnalysisRecord.Auditors.Add(user);
            if (!ModelState.IsValid)
            {
                return PartialView("InternalAuditRecordForm", criticalAnalysisRecord);
            }

            try
            {
                criticalAnalysisRecordRepository.Save(criticalAnalysisRecord);
            }
            catch (Exception )
            {
                var view = criticalAnalysisRecord.InternalAuditRecordID == 0 ? "New" : "Edit";
                return Json(new { success = false }).Error("Ocorreu um erro durante a solicitação.");
            }
            return Json(new { success = true }).Success("A ata foi cadastrada com sucesso!");
        }
    
asked by anonymous 17.07.2017 / 13:31

0 answers