ActionLink的Bootstrap模式弹出窗口未显示

时间:2017-03-07 16:43:12

标签: jquery html ajax asp.net-mvc

我在学生页面上有一个创建新表单链接,以创建一个新学生,我希望使用bootstrap将其显示为模式弹出窗口,而不是转到另一个页面并创建学生。

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

[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);
        }

在StudentController中创建操作

private async void button1_Click(object sender, EventArgs e)
{
   this.button1.Enabled = false; 
   var someTask = Task<int>.Factory.StartNew(() => slowFunc(1, 2)); 
   await someTask;  
   this.label1.Text = "Result: " + someTask.Result.ToString(); 
   this.button1.Enabled = true;
}

4 个答案:

答案 0 :(得分:1)

您正在将JS挂钩和Bootstrap按钮类应用于p标记,这两个标记都不受支持。您的链接应该包含以下内容:

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

答案 1 :(得分:1)

您遇到了麻烦,因为您希望将表单放在模式中,而是将操作链接放到另一个页面上,该页面上有一个表单。您必须将表单从您不想要的页面复制出来并将其粘贴到模态的主体内。然后,当您在此处提交表单时,它将触发您的表单在控制器中指向的操作,操作将处理表单数据并返回视图,即刷新页面。因此,您应该编辑表单操作以重定向到索引视图或watever视图,它具有此模式。正如你所说,你正在考虑使用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>

提交输入将提交您的表单并为您在网址中指定的操作发帖。这本质上与写作相同:

  @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。另外你使用了一个视图模型,我现在不打算输入!!

答案 2 :(得分:0)

我建议你创建一个按钮来获取你的模态。 <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">Open Modal</button>,如果您希望按钮显示为动作链接,则可以通过css执行此操作。

答案 3 :(得分:0)

如果您想使用 Jquery 打开模态弹出窗口

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>