剃刀页面中的确认模态后的信息模态

时间:2018-09-17 05:34:13

标签: c# asp.net asp.net-mvc razor

我想显示一个信息模式,内容为“记录已成功删除”。单击确认模式内的按钮后。

这是我的代码,用于显示确认模式

控制器

public IActionResult Delete()
{
   return PartialView("_ModalDelete");
}

_ModalDelete.cshtml

@using Data.ViewModels.Modal

@using (Html.BeginForm())
{
    @await Html.PartialAsync("_ModalHeader", new ModalHeader { Heading = "Delete" })

    <div class="modal-body form-horizontal">
        Are you sure you want to delete this record?
    </div>

    @await Html.PartialAsync("_ModalFooter", new ModalFooter { SubmitButtonText = "Delete" })
}

示例屏幕截图:

enter image description here

这部分似乎还可以。没有遇到任何问题。但是,单击“删除”按钮后,它将像整个视图一样显示我的模态。见下文:

enter image description here

这是我的代码:

控制器-用于在单击删除按钮后发布数据

[HttpPost]
public async Task<IActionResult> Delete(int id)
{
    try
    {
        var validationResult = await new RegionHandler(_regionService).CanDelete(id);
        if (validationResult == null)
        {
            await _regionService.DeleteById(id);

            return PartialView("_ModalInfo", new Tuple<string, string>(Constants.Message.Info, Constants.Message.RecordSuccessDelete));
        }

        ModelState.AddModelError(validationResult);
    }
    catch (Exception ex)
    {
        var exceptionMessage = await Helpers.GetErrors(ex, _emailService);
        ModelState.AddModelError(new ValidationResult(exceptionMessage));
    }

    ModelState.AddModelError(string.Empty, "Invalid delete attempt.");

    return PartialView("_ModalInfo", new Tuple<string, string>(Constants.Message.Error, ModelState.ToString()));
}

_ModalInfo.cshtml

@using Data.ViewModels.Modal
@model Tuple<string,string>

@await Html.PartialAsync("_ModalHeader", new ModalHeader { Heading = Model.Item1})

<div class="modal-body form-horizontal">
    @Model.Item2
</div>

@await Html.PartialAsync("_ModalFooter", new ModalFooter { CancelButtonText = "OK", OnlyCancelButton = true})

2 个答案:

答案 0 :(得分:0)

提交表单后,您将往返于服务器,服务器将发布一个全新的html页面(即使您的html代码只是部分)。

要删除问题模态并将其替换为原始页面(区域列表)中的消息模态,您将必须使用javascript(用于帖子和替换)。

如果您要坚持往返,请使Delete方法返回完整的html页面,该页面集成了消息对话框(例如region-list集成了问题对话框)。

答案 1 :(得分:0)

最后找到了答案。因此,基本上我只是修改了所有内容,以便仍可以从控制器进行模型验证。

这里是我的代码:

用于表格标记

<tr>
    <td>
        @Html.DisplayFor(modelItem => item.RegionName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.RegionCode)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.RegionKey)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Description)
    </td>
    <td class="text-center">
        <a asp-action="Edit" asp-route-id="@item.RegionId"><i class="fa fa-edit text-info"></i></a>
        <a href="#" onclick="showDeleteConfirmation('@string.Format(Constants.Message.DeletePrompt, item.RegionName)', event, @item.RegionId)"><i class="fa fa-trash text-danger"></i></a>
    </td>
</tr>

它在下面调用javascript函数的地方:

@section Scripts{
    <script type="text/javascript">
        function showDeleteConfirmation(message, event, id) {
            event.preventDefault();

            showConfirmationModal(message).then(function () {
                $("#id").val(id);
                $("#formDelete").submit();
            });
        }
    </script>
}

其中showConfirmationModal()是一个使用bootbox.js的Promise函数(该库包装了引导程序模版,以便于使用)。

site.js

function showConfirmationModal(message, title = "Confirm", size = "medium", confirmText = "Yes", canceltext = "No") {
    const deffered = $.Deferred();

    bootbox.confirm({
        title: title,
        message: message,
        size: size,
        buttons: {
            confirm: {
                label: confirmText,
                className: "btn-success"
            },
            cancel: {
                label: canceltext,
                className: "btn-danger"
            }
        },
        callback: function (result) {
            if (result) {
                deffered.resolve(result);
            } else {
                deffered.reject(result);
            }
        }
    });

    return deffered.promise();
}

在回调时,它将提交以下隐藏的表单。当然不要忘记设置要删除的ID。

隐藏的“删除”操作表格

<form method="post" asp-action="Delete" id="formDelete" class="hidden">
    <input type="hidden" id="id" name="id" />
    <input type="hidden" asp-for="Item1.RegionName" name="RegionName" />
    <input type="hidden" asp-for="Item1.Page" name="Page" />
    <input type="hidden" asp-for="Item1.SortBy" name="SortBy" />
    <input type="hidden" asp-for="Item1.SortOrder" name="SortOrder" />
</form>

为了显示信息消息(成功删除),我创建了PartialView以便在临时数据或TempData中存在数据集时显示模式。这是在_Layout.cshtml页下添加的:

_ModalScriptsInit.cshtml

@using Data.Utilities
@{
    var text = TempData[Constants.Common.ModalMessage];
    if (text != null && !text.Equals(string.Empty))
    {
        <script type="text/javascript">
            showDefaultModal("@text");
        </script>
    }
}

因此,在控制器中,一旦成功删除,我将使用其密钥设置TempData,如下所示:

控制器

[HttpPost]
public async Task<IActionResult> Delete(int id, RegionSearchViewModel searchViewModel)
{
    try
    {
        var validationResult = await new RegionHandler(_regionService).CanDelete(id);
        if (validationResult == null)
        {
            await _regionService.DeleteById(id);
            TempData[Constants.Common.ModalMessage] = Constants.Message.RecordSuccessDelete;

            return RedirectToAction(nameof(List), searchViewModel);
        }

        ModelState.AddModelError(validationResult);
    }
    catch (Exception ex)
    {
        var exceptionMessage = await Helpers.GetErrors(ex, _emailService);
        ModelState.AddModelError(new ValidationResult(exceptionMessage));
    }

    ModelState.AddModelError(string.Empty, "Invalid delete attempt.");

    return RedirectToAction(nameof(List), searchViewModel);
}

我目前尚不确定这是否是最好的方法。请提出有关如何改进此代码的建议。谢谢!