我正在使用.NET Framework 4.5和Bootstrap v3.3.6开发ASP.NET MVC项目。
我的需求是创建一个模态表单。
我尝试了以下方法:
Created a modal container in the main layout
<div id="modal-container" class="modal fade" tabindex="-1" role="dialog" style="border: 5px solid #3A87AD;"> <a href="#close" title="Close" class="modal-close-btn">x</a> <div class="modal-content" style="width:500px !important; margin: 10px auto !important;"> <div class="modal-body"></div> </div> </div>
Added js to make internal Ajax call to inject content in a partial view
$(function () { $('body').on('click', 'modal-link', function (e) { e.preventDefault(); $(this).attr('data-target', '#modal-container'); $(this).attr('data-toggle', 'modal'); }); $('body').on('click', 'modal-close-btn', function() { $('modal-container').modal('hide'); }); $('#modal-container').on('hidden.bs.modal', function(){ $(this).removeData('bs.modal'); }); });
Created a partial view that to load in a modal dialog
<div class=" "> <div class="modal-title" style="color: #3A87AD;"> <h3> Add Content</h3> </div> <br /> @using (Html.BeginForm("Create", "Place", FormMethod.Post)) { <div class="row-fluid"> Enter Content </div> <div class="row-fluid"> @Html.textAreaFor(m => m.Text, new { style="width:400px; height:200px;"}) </div> <div class="row-fluid"> <div class="col-md-4 col-md-offset-4"> <button type="submit" id="btnSave" class="btn btn-sm">Save</button> <button type="button" class="btn btn-sm" data-dismiss="modal">Cancel</button> </div> </div> } </div> <script type="text/javascript"> $(function () { $('#btnSave').click(function () { $('#modal-container').modal('hide'); }); }); </script>
Created action to return the partial view and to process the results of the post
public ActionResult CreateModal() { return PartialView("_CreateModal"); } [HttpPost] public ActionResult CreateModal(Place model) { return RedirectToAction("Index"); }
Created an action link to show the modal when clicked
@Html.ActionLink("Click me", "CreateModal", "Place", null, new { @class = "img-btn-addcontent modal-link", title = "Add Content" })`
![enter image description here](https://istack.dev59.com/9TIto.webp)