我有一个局部视图,显示在Bootstrap模态窗口中。视图是用于创建对象实例的Ajax表单。
单击“保存”按钮时,对象将正确添加到数据库,但模式保持打开状态。我希望在单击保存按钮时关闭模式。
模态中的按钮:
<div class="modal-footer">
<button class="btn btn-inverse" type="submit" id="btn-create-property-save">Save</button>
</div>
然后在我的脚本文件中:
$('#btn-create-property-save').click(function(e) {
e.preventDefault();
$('#create-residential-property-modal').modal('hide');
return false;
});
当我点击按钮时,模态保持打开状态。
我不太确定并且可能导致问题的一件事是我在CreateObject
控制器操作中返回的内容。目前我只有return PartialView();
。鉴于上述情况,我应该回到这里?
编辑:添加了代码以显示如何加载模态。
<div class="modal hide fade in" id="create-residential-property-modal" data-url="@Url.Action("LandlordProperties", "Landlords")">
<div id="create-property-container"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#show-create-property-modal').click(function () {
var url = $('#create-residential-property-modal').data('url');
$.get(url, function (data) {
$('#create-property-container').html(data);
$('#create-residential-property-modal').modal('show');
});
});
});
</script>
答案 0 :(得分:1)
以下是我过去的表现。
第1步,使用Ajax提交表单:
@using (Ajax.BeginForm("Create", new AjaxOptions()
{
OnFailure = "Modal.onAjaxFailure",
OnSuccess = "Modal.onAjaxSuccess"
}))
{
<div class="form-body">
@Html.TextAreaFor(model => model.Text, new { rows = "3" })
</div>
<div class="form-footer">
@Html.ValidationMessageFor(model => model.Text)
@Html.ValidationSummary(true)
@CustomHelpers.SubmitButton("Add Comemnt")
</div>
}
步骤2,返回JSON结果以显示成功/失败消息:
[HttpPost]
public ActionResult Create(CommentCreateModel model)
{
if (ModelState.IsValid)
{
//Do your database insert etc here...
return Json(new { error = false, message = "Comment added" });
}
else
{
return Json(new { error = true, message = "The values entered are not valid" });
}
}
第3步,处理响应(我的示例是在TypeScript中):
export function onAjaxFailure(xhr, status, error) {
//Show notifications for AJAX errors
$.notify({
type: "error",
text: error
});
}
export function onAjaxSuccess(data, status, xhr) {
if (data.error) {
$.notify({
type: "error",
text: data.message
});
}
else {
$('.modal').modal('hide'); //Hides modal window
//Show message/anything else here
}
}