C# 控制器数据到 JavaScript 但是当使用 RETURN JSON 模态消失/成功后刷新 ajax 模态

Posted

技术标签:

【中文标题】C# 控制器数据到 JavaScript 但是当使用 RETURN JSON 模态消失/成功后刷新 ajax 模态【英文标题】:C# Controller data to JavaScript But when using RETURN JSON Modal Disappears/ Refresh ajax modal after success 【发布时间】:2020-06-16 09:24:41 【问题描述】:

我的模态中有一些数据想传递给 javascript。当我使用“return json”确实有效时,但我失去了我的模态。我不再能够对我正在使用的模式进行任何控制。它只是变成一个空的模式。在我的 ajax 完成上,我猜测也许我可以在部分视图中重新加载控件,或者以不同于返回 json 的方式将数据传递给我的 JS。

    @using (Ajax.BeginForm("CreateSQcontact", "Service", new AjaxOptions()  HttpMethod = "POST", UpdateTargetId = "ajaxContact", OnSuccess = "contactSuccess" ))

    <div class="modal" id="AddSQcontact" tabindex="-1" role="dialog" aria-labelledby="lblAjaxContact" aria-hidden="true" style="z-index:1060;">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="text-center"><b>Create Contact</b></h3>                    
                </div>
                <div class="modal-body" id="ajaxContact">
                    @html.Partial("SQcontact")
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                    <input type="submit" class="btn btn-success" value="Create Contact" />
                </div>
            </div>
        </div>
    </div>

    function contactSuccess(data) 
        if (data.Status == "Created") 
            $("#AddSQcontact").modal("hide");
            var modalX = $('#' + data.Modal);
            var newObj = data.Object;
            var custDDL = modalX.find('.modal-body').find('#ServiceVM_CustomerName').val();
            var sn2DDL = modalX.find('.modal-body').find('#ServiceVM_SN2').val();
            var partI = displayContactsDDL(custDDL, sn2DDL, modalX, newObj);
        
    
    function displayContactsDDL(customer=null, sn2=null, modalID=null, newObj=null) 
        return $.ajax(
            url: '@Url.Action("SearchContactsList", "Service")',
            data:  customer: customer, sn2: sn2 ,
            dataType: 'json',

        ).done(function (data) 
            var dropdown = modalID.find('.modal-body').find('#ServiceVM_ContactName');
            dropdown.empty();
            $.each(data, function () 
                dropdown.append(
                    $('<option></option>').val(this.Value).html(this.Text)
                );
            );
            if ($.isNumeric(newObj)) 
                dropdown.val(newObj);
                displayContactData(newObj, modalID)
            
        );
    
[HttpPost]
        [ValidateAntiForgeryToken]    
        public ActionResult CreateSQcontact(ServiceModel model)
        
            string action = "";
            ServiceModel serviceModel = TempData["ServModel"] == null ? serviceModel = new ServiceModel() : TempData["ServModel"] as ServiceModel;
            ModalResponse myData = null;
            if (TempData["MR"] != null)
            
                TempData["MR"] = TempData["MR"] as ModalResponse;
                myData = TempData["MR"] as ModalResponse;
            

            if (ModelState.IsValid)
            
                int customerID = 0;
                var numericPhone = "";                
                if(model.ServiceContact.ContactPhone != null)
                
                    numericPhone = new string(model.ServiceContact.ContactPhone.Where(char.IsNumber).ToArray());
                
                if(model.ServiceContact.ContactCustomer != null)
                
                    customerID = context.Customers.Where(c => c.Name == model.ServiceContact.ContactCustomer)
                                        .Select(x => x.ID).FirstOrDefault();
                

                var contact = new Serv_Contacts()
                
                    Contact = model.ServiceContact.ContactName,
                    Phone = model.ServiceContact.ContactPhone,
                    Email = model.ServiceContact.ContactEmail,
                    SN2 = model.ServiceContact.ContactSN2,
                    CustomerID = customerID
                ;

                context.Serv_Contacts.Add(contact);
                context.SaveChanges();
                ModelState.Clear();
                if(myData != null)
                
                    //myData.Object = contact.Contact;
                    myData.Object = contact.Contact_ID;
                    TempData["MR"] = myData as ModalResponse;
                
                serviceModel = LoadVirtualService(serviceModel);
                TempData["ServModel"] = serviceModel;

                //ModalResponse parameter = TempData["MR"]==null ? parameter=new ModalResponse() : TempData["MR"] as ModalResponse;
                //myData = myData == null ? myData = new ModalResponse() : myData;
                myData = myData ?? (myData = new ModalResponse());

                return Json(myData, JsonRequestBehavior.AllowGet);
                string serializedData = JsonConvert.SerializeObject(myData);
               // return new HtmlString(serializedData.ToString());
            

            serviceModel = LoadVirtualService(serviceModel);
            TempData["ServModel"] = serviceModel as ServiceModel;

            return PartialView("SQcontact", serviceModel);
        

【问题讨论】:

【参考方案1】:

这是我的解决方案,我得到了它的工作!

CONTROLLER
myData = myData ?? (myData = new ModalResponse());
string serializedData = JsonConvert.SerializeObject(myData);
ViewBag.SMR = serializedData;
return PartialView("SQcontact", serviceModel);

VIEW
@Html.Hidden("SMRdata", (object)ViewBag.SMR)

JAVASCRIPT
function contactSuccesses() 

            var modalC = $('#AddSQcontact');
            ///var txtContactName = modalC.find('.modal-body').find('#ServiceContact_ContactName').val();

            var txtsmrdata = modalC.find('.modal-body').find('#SMRdata').val();
            var jsonObj = JSON.parse(txtsmrdata);
            var modalX = "", status = "", objID = 0;

            if (jsonObj != null || jsonObj != "") 
                status = jsonObj.Status;

                if (jsonObj.Modal != "") 
                    modalX = $('#' + jsonObj.Modal);
                
                if (jsonObj.Object != 0) 
                    objID = jsonObj.Object;
                
            

            if (status == "Created") 
               // alert('in here');
                if (modalX != "") 
                    var custDDL = modalX.find('.modal-body').find('#ServiceVM_CustomerName').val();
                    var sn2DDL = modalX.find('.modal-body').find('#ServiceVM_SN2').val();
                    var nextPart = true;
                
                if (nextPart) 
                    displayContactsDDL(custDDL, sn2DDL, modalX, objID);
                
            
    

【讨论】:

以上是关于C# 控制器数据到 JavaScript 但是当使用 RETURN JSON 模态消失/成功后刷新 ajax 模态的主要内容,如果未能解决你的问题,请参考以下文章

如何在 C# 中将数据发送到 ASP.NET Core MVC 控制器?

通过 Javascript 将 DatePicker 值传递给 C# 控制器

从 JavaScript 向不同文件夹中的 C# 控制器进行 ajax 调用

创建从 C# 到 JavaScript 的动态 JSON

如何将 javascript 对象传递给 C# MVC 4 控制器

hcs12 microcontroller 笔记