【问题标题】:ASP.NET MVC 'Create' Action in Bootstrap Modal to Update Index from separate view/controller引导模式中的 ASP.NET MVC“创建”操作以从单独的视图/控制器更新索引
【发布时间】:2019-06-27 21:29:56
【问题描述】:

我有一个名为“Reviews”的视图/控制器,我想要一个引导模式弹出窗口,显示来自“ReviewChecklist”控制器的“创建”操作。这一切都正确显示,但我需要提交这篇文章以将清单数据保存到数据库中。这样做会导致它崩溃并呈现错误的页面,而不是仅仅关闭模式弹出窗口。

我也有上面呈现的“ReviewChecklist”的索引,所以理想情况下也应该更新。

不确定我是完全错误地处理了这个问题还是得到了一些不太正确的东西,在此先感谢。

“审查”视图

<div class="form-group">
            @{
                Html.RenderAction("Index", "ReviewChecklists", new { reviewId = Model.Id, viewOnly = false });
            }

            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#checklistModal">
                Launch demo modal
            </button>
            <div class="modal fade" id="checklistModal" tabindex="-1" role="dialog" aria-labelledby="checklistModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="checklistModalLabel">Review Checklist</h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        @using (Html.BeginForm("Create", "ReviewChecklistsController", FormMethod.Post, new {Id = "checklistForm" }))
                        {
                            <div class="modal-body">
                                @{Html.RenderAction("Create", "ReviewChecklists", new { reviewId = Model.Id });}
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-success">Save Checklist</button>
                            </div>
                        }
                    </div>
                </div>
            </div>
        </div>

'ReviewChecklist' 控制器:

[HttpPost]
//[ValidateAntiForgeryToken] Causes issues with the modal dialog
        public async Task<ActionResult> Create([Bind(Include = "Id,ReviewId,ChecklistId,Status")] ReviewChecklist[] reviewChecklist)
        {
            foreach (ReviewChecklist item in reviewChecklist)
            {
                db.ReviewChecklists.Add(item);
            }
            await db.SaveChangesAsync();
            return PartialView();
            //return RedirectToAction("Create", "Reviews", new { reviewId = reviewChecklist[0].ReviewId });
        }

脚本代码:

如果你还需要什么,请评论:)

// prepare the form when the DOM is ready 
$(document).ready(function () { 
    alert('setting up form');
    var options = { 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success: showResponse,  // post-submit callback 
        error: handleError
    }; 

    // bind form using 'ajaxForm'
    $('#checklistForm').ajaxForm(options); /// give your create form an ID
    alert('form setup complete');
}); 

// pre-submit callback 
function showRequest(formData, jqForm, options) { 
  //// things you can do before form submit like loaders
    alert('showRequest');
    return true;
} 

// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
 //// things you can do after the response 
    alert('showResponse');
    alert(responseText);
  if(responseText == 1)
   $("#checklistModal").modal("hide");
   /// show toast or somthing for saving data successfully
} 

function handleError(xhr, textStatus, error) {
    alert('error');
    alert(textStatus);
}

jQuery.Form 插件已通过 Nuget 添加并添加到包中,如下所示:

bundles.Add(new ScriptBundle("~/bundles/jqueryform").Include(
                    "~/Scripts/jquery.form*"));

然后像这样在_Layout.cshtml中引用

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

我现在面临的问题是提交完成后并没有关闭modal,而是只渲染页面的所有源代码?我也没有看到 showRequest 或 showResponse 的警报,但显示了表单设置的警报。

【问题讨论】:

    标签: asp.net-mvc bootstrap-modal jquery.form.js


    【解决方案1】:

    1.保持 HTML 不变,但要提供创建的 ID。确保它也没有嵌套在任何其他形式中。

    2。在 here 的布局中包含此 库(也可作为 Nuget 包提供)

    这是一个 jQuery 表单插件,可让您轻松且不显眼地升级 HTML 表单以使用 AJAX。

    3.控制器

        [HttpPost]
        //[ValidateAntiForgeryToken] Causes issues with the modal dialog
        public async Task<ActionResult> Create([Bind(Include = 
           "Id,ReviewId,ChecklistId,Status")] ReviewChecklist[] reviewChecklist)
        {
            foreach (ReviewChecklist item in reviewChecklist)
            {
                db.ReviewChecklists.Add(item);
            }
            await db.SaveChangesAsync();
    
            return Json(1, JsonRequestBeahvaoir.AllowGet); /// return 1 or 0 or as per requirements or anything, the response you can handle in jQuery showResponse() method later.
        }
    

    4.脚本

    // prepare the form when the DOM is ready 
      $(document).ready(function() { 
         var options = { 
               beforeSubmit:  showRequest,  // pre-submit callback 
               success:       showResponse  // post-submit callback 
         }; 
         // bind form using 'ajaxForm' 
         $('#myForm1').ajaxForm(options); /// give your create form an ID
      });     
    
    // pre-submit callback 
      function showRequest(formData, jqForm, options) { 
          // things you can do before form submit like loaders
          return true; 
        } 
    
     // post-submit callback 
      function showResponse(responseText, statusText, xhr, $form)  { 
         // things you can do after the response 
          if(responseText == 1)
           $("#checklistModal").modal("hide");
           // show toast or somthing for saving data successfully
        } 
    

    【讨论】:

    • 谢谢,我会在周末试一试,让你知道我的进展:)
    • 是的,只要你有时间:)
    • 试一试,并取得了一些进展。将 jQuery.Form 添加为 nuget 包并如上所述引用它。击中控制器并正确保存,但它从未击中我在 showRequest 或 showResponse 中的任何警报。有什么想法吗?
    • @RyanThomas 您添加了哪个库?因为我提到的库不在nuget上
    • @RyanThomas 是正确的,你有没有给表单一个 ID
    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多