【问题标题】:Bootstrap modal popup for ActionLink not showingActionLink 的引导模式弹出窗口未显示
【发布时间】:2017-03-08 04:14:12
【问题描述】:

我的学生页面上有一个新建表单链接,用于创建一个新学生,我想使用引导程序将其显示为模式弹出窗口,而不是转到另一个页面并创建学生。

它目前作为 Html.ActionLink 工作,但我很难在弹出窗口的正文中显示表单。后来我也想用它用AJAX插入数据,但是想先实现modal popup。

<script src="~/Scripts/jquery-3.1.1.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap.js"></script>
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

@if (User.IsInRole("Admin"))
{
    <p class="btn btn-primary" data-toggle="modal" data-target="#myModal">

        @Html.ActionLink("Create New", "Create", null, new { @id = "create" })

        <div class="modal fade" id="myModal">
            <div class="modal-dialog">
                <div class="modal-content">

                    <div class="modal-header">
                        <a href="#" class="close" data-dismiss="modal">&times;</a>
                        <h3 class="modal-title">Create Modal</h3>
                    </div>

                    <div class="modal-body">
                        @Html.ActionLink("Create New", "Create", null, new { @id = "create" })

                    </div>

                    <div class="modal-footer">
                        <a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a>
                        <a href="#" class="btn btn-success" >Create</a>

                    </div>
                </div>
            </div>
        </div>
    </p>

在 StudentController 中创建动作

[Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,LastName, FirstMidName, EnrollmentDate, PaymentDue")]
           Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    studentRepository.InsertStudent(student);
                    studentRepository.Save();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException /* dex */)
            {
                //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
                ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
            }
            return View(student);
        }

【问题讨论】:

    标签: jquery html ajax asp.net-mvc


    【解决方案1】:

    您遇到了麻烦,因为您想将表单放入模态框内,但您已将操作链接放置到另一个页面上,该页面上有一个表单。您必须从不需要的页面上复制表单并将其粘贴到模态框的正文中。然后,当您在此处提交表单时,它将触发您的表单在控制器中指向的操作,该操作将处理表单数据并返回一个视图,也就是刷新页面。因此,您应该编辑表单操作以重定向到索引视图或具有此模式的水视图。正如您所说,您正在考虑使用 ajax,可能是因为您不希望页面刷新。无论如何,我会在这里制作一个模拟表单,因为我不知道您的表单是什么样子或您的 HttpPost 操作。附:我正在手机上打字。

    重新开始。

      // here is a button which will open up the modal.  forget about using an actionlink to do this.
      <button type="button" class="btn btn-info btn-lg"  data-toggle="modal" data- target="#myModal">Create New</button>
    
      //here is a functioning modal
      <div id="myModal" class="modal fade"  role="dialog">
        <div class="modal-dialog">
    
          <!-- Modal content-->
          <div class="modal-content">
            <div class="modal-header">
             <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">Create Something</h4>
            </div> 
            //wrap your modal-body and your modal- footer in a form. You can copy the begin form from  your other page. You may have problems here  because if this is a scaffolded crud that form most  likely uses another model(not modal) which you  return to it from an action. What you can do is  make an html form and name your inputs correctly  and post it to your action.
    
            <form action="/ControllerName/ActionName" method="post">
            <div class="modal-body">
              First name: <input type="text" name="fname">     <br>
              Last name: <input type="text" name="lname"><br>           
            </div>
            <div class="modal-footer">
              <a class="btn btn-default" data-dismiss="modal">Close</a>
    
            <input type="submit" class="btn btn-success pull-right"  value="Save">          
        </div>
        </form>
         </div>
       </div>
      </div>
    

    提交输入将提交您的表单并发布到您在 url 中指定的操作。这本质上和写一样:

      @using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
      {
    
          <div class="modal-body">
             First name: <input type="text" name="fname">     <br>
             Last name: <input type="text" name="lname"><br>           
           </div>
           <div class="modal-footer">
             <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    
      <input type="submit" class="btn btn-success  pull-right"  value="Save">       
      </div>
    
     }
    

    我不知道您是否需要验证摘要或防伪令牌。您必须检查要复制的表格。

    那么您的操作将如下所示:

    public class ControllerName : Controller
    {
        public ActionResult Index()
        {
            // Add action logic here
            return View();
        }
    
        [HttpPost]
        public ActionResult ActionName(string fname, string lname)
        {
            // do something with fname and lname. Thenaming of your html inputs and the parameters you recieve here are important. If the post action has a required parameter that you do not post it will give you a 404 or something.
    
            //redirec to whatever page has the modal on
            return View("Index")
         }       
     }
    

    回答编辑:

    因此,对于您的情况,我建议您忘记为创建表单传回模型。它将模型返回到创建页面的原因是,如果一个人填写表单并且保存错误,该操作将返回包含用户填写的所有字段的对象,这样他就不必填写又出来了。您可以在表单的 HttpPost 操作中看到这一点。当您最初创建条目时,您不需要模型,因为无论如何您都是从所有字段开始为空的。 (仅供参考 - 您应该意识到将模型返回到“编辑”页面的明显需要,因为您正在编辑已经保存在数据库中的值..)所以这是您的选择 - 如果您想返回如果保存失败,您将不得不使用视图模型。否则,您可以制作一个标准的 html 表单并将其发布到您的操作中。我可以在这里做一个例子。

    这是你的表格:

    @using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
      {
        @Html.AntiForgeryToken()
          <div class="modal-body">
             First name: <input type="text" name="FirstMidName">     <br>
             Last name: <input type="text" name="lname"><br>           
             //do you need a date picker here????
             Enrollment Date: <input type="text" name="EnrollmentDate"><br>
    
            Payment Due: <input type="text" name="PaymentDue"><br>
    
           </div>
           <div class="modal-footer">
             <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    
      <input type="submit" class="btn btn-success  pull-right"  value="Save">       
      </div>
    
     }
    

    这是你的控制器:

        [Authorize(Roles = "Admin")]
        [ValidateAntiForgeryToken]
        [HttpPost]
    
        public ActionResult Create(string LastName, string FirstMidName, string EnrollmentDate, string PaymentDue)
        {
    
           // If you do not have validation on the front end you at tge very least need to put some null checks here based on you required fields. I remover the model state check as we are not passing through a model anymore. So:
            if (FirstMidName != ""){
            try
            {
                Student student = new Student();
                student.LastName = LastName;
                student.FirstMidName = FirstMidName;
    
               //you need to handle how this date is parsed here
                student.EnrollmentDate =DateTime.Parse(EnrollmentDate);
    
                //if this is a bool you may need to do some logic here depending on what values your form gives you. Maybe if (PaymentDue == "checked"){student.PaymentDue = true} else { student.PaymentDue = false}
              //if payment due is monetry value you must be very catefull about the way you parse decimals/floats with the decimal point and culturr information. You will need to do some research here.
       student.PaymentDue = PaymentDue;
    
                    studentRepository.InsertStudent(student);
                    studentRepository.Save();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException /* dex */)
            {
                //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
                ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
            }
            }
            //see i removed the old return view with a model here which was incase there was a problem saving.
            return RedirectToAction("Index") ;
        }
    

    这是一个粗略的想法。我在手机上打字,哈哈。我建议从您现有的创建表单中复制所有验证元素并将它们粘贴到您的新表单模式中,包括验证摘要(如果有的话)。您可以在 chrome 中打开现有表单并右键单击以查看页面源代码,然后从那里复制表单的呈现 html,这样您就不会丢失任何现有的验证和输入。但是,如果您愿意,请保留 @html.Beginform 和 antiforgerytoken。 Alyernatively 你应该使用一个视图模型,我现在不想打字了!!

    【讨论】:

    • 感谢您的信息。我对 jQuery 和 AJAX 非常陌生,我正在努力解决它。如果我需要使用 jQuery 来创建模态弹出窗口,它会改变您在帖子中的布局格式吗?
    • 不,只要您在页面上正确设置了表单,使用 jquery 或默认引导程序都没有关系。但是我建议使用默认的引导模式,它工作正常。另请注意,我已经编辑了模式上的关闭按钮,因为您放入表单中的按钮将执行提交。所以我会把它改成anchortag。
    • 正如您所提到的,它给我在模态正文部分中使用开始表单时带来了问题,因为我不能在视图中使用多个模型引用。当我尝试创建一个普通的 html 表单时,我无法创建验证器或 AntiForgery。
    • 好的,这里有一些选项。不要担心它可能会发生的变化。您可能要考虑的第一个选项是使用视图模型。你知道什么是视图模型吗?如果您正在使用 mvc 进行开发,您将不​​得不学习,因为您将再次遇到这种情况。视图模型允许您将两个或多个模型返回到视图以及您想要返回的任何其他数据。但是,对于创建,尤其是以这种方式,您不需要返回表单的模型。我将在我的答案中输入一些编辑内容。
    【解决方案2】:

    您正在将 JS 挂钩和 Bootstrap 按钮类应用到 p 标记,两者都不支持。你的链接应该有这些:

    @Html.ActionLink("Create New", "Create", null, new { id = "create", @class = "btn btn-primary", data_toggle = "modal", data_target = "#myModal" })
    

    【讨论】:

    • 谢谢,它现在正在显示弹出框。但它显示了站点的完整nav-bar,并且没有在页眉中显示关闭选项的“X”,也没有在页脚中显示cancel 按钮?
    【解决方案3】:

    我建议您创建一个按钮来获取您的模式。 &lt;button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal"&gt;Open Modal&lt;/button&gt;,如果你想让按钮看起来像一个动作链接,你可以通过 css 来实现。

    【讨论】:

      【解决方案4】:

      如果你想用Jquery打开modal popup

      JS

      $(function () {
                  $('#create').on('click', function (e) {
                      e.preventDefault();
                      $('#myModal').modal('show');
                  });
              });
      

      HTML

      <body>
          @Html.ActionLink("Create New", "Create", null, new { @id = "create" })
      
          <div class="modal fade" id="myModal">
              <div class="modal-dialog">
                  <div class="modal-content">
      
                      <div class="modal-header">
                          <a href="#" class="close" data-dismiss="modal">&times;</a>
                          <h3 class="modal-title">Create Modal</h3>
                      </div>
      
                      <div class="modal-body">
      
                      </div>
      
                      <div class="modal-footer">
                          <a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a>
                          <a href="#" class="btn btn-success">Create</a>
      
                      </div>
                  </div>
              </div>
          </div>
      </body>
      

      【讨论】:

        猜你喜欢
        • 2015-02-16
        • 1970-01-01
        • 2021-08-31
        • 1970-01-01
        • 2016-04-25
        • 1970-01-01
        • 1970-01-01
        • 2020-08-01
        • 1970-01-01
        相关资源
        最近更新 更多