【问题标题】:TempData Dropping DataTempData 删除数据
【发布时间】:2020-10-30 15:33:39
【问题描述】:

我试图在返回的 PartialView() 上保留一个 TempData 值。它在一个帖子中正常工作,但在另一个帖子中不能正常工作,我被阻碍了。

在以下操作中,它可以正常工作,并且值通过 javascript 重定向到使用该值的操作:

[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult DeletetheFile(int attachmentid, string issueId)
{          

    string response = _adoSqlService.DeleteAttachment(attachmentid);
    TempData["ID"]= issueId;
    TempData.Keep();
     return PartialView("_DeleteFile");

}

在接下来的动作中,它被正确设置(参见第一张图片),但是当它到达与我展示的第一个相同的动作时,它已经改变了(参见第二张图片)。

[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult EditFile(IFormCollection collection)
{
    AttachmentModel model = new AttachmentModel();

    model.attachmentId = Convert.ToInt32(collection["attachmentId"]);
    model.aIssueAttachmentDescription = collection["aIssueAttachmentDescription"];
    string response = _adoSqlService.EditFileDescription(model);
    TempData.Remove("ID");
    TempData["ID"] = collection["issueId"];
    TempData.Keep();
    return PartialView("_EditFile");
 }

当它到达我需要的地方时,它现在返回 [string1] 而不是 20-003。

上述两个操作都针对模式弹出窗口中的局部视图运行。以下 javascript 捕获模态操作并将结果重定向到问题/编辑控制器/操作。

$('body').on('click', '.relative', function (e) {
        e.preventDefault();
        var form = $(this).parents('.modal').find('form');
        var actionUrl = form.attr('action');
        var dataToSend = form.serialize();
        $.post(actionUrl, dataToSend).done(function (data) {
            $('body').find('.modal-content').html(data);
            var isValid = $('body').find('[name="IsValid"]').val() == 'True';
            if (isValid) {
                $('body').find('#modal-container').modal('hide');
                window.location.href = "/Issue/Edit";
            }

        });
    })

重定向似乎发生了,因为在这两种情况下都调用了编辑操作。只是在第二种情况下,它没有得到正确的 TempData 值。这是 Edit 操作的开始,它位于与上述 2 个操作不同的控制器中:

public ActionResult Edit(string id)
{
    if (id == null)
    {
        id = TempData["ID"].ToString();                
    }

---------更多评论 因此,在过去 4 小时的工作后,我想出了一个解决方法。我不确定这是否是正确的技术。我最终做的是在部分视图上添加一个隐藏的输入字段,然后解析该值的 ajax 响应。

var issueid = $(response).find('[name="issueidSaved"]').val();
window.location.href = "/Issue/Edit/?id=" + issueid

我现在担心的是 issueid 现在包含在查询字符串中并且在 URL 中可见。

这是正确的方法还是我应该重新使用 TempData 并尝试让它发挥作用?

更新 希望我能更好地解释这一点。目标是在与我的编辑页面(问题/编辑)相关联的问题控制器中的以下操作中获取 TempData 值:

public ActionResult Edit(string id)
{
    if (id == null)
    {
        id = TempData["ID"].ToString();                
    }

我的编辑页面上有一个模式,其中填充了不同的局部视图,具体取决于填充它的内容。部分视图使用附件控制器,而编辑视图使用问题控制器。我使用 Javascript/ajax 从部分视图捕获提交以关闭模式并重定向到编辑视图,因此受部分视图影响的数据的刷新反映在编辑视图上。当我提交 _DeleteFile 时,TempData 值正常工作,但当我在模态中提交 _EditFile 部分视图时却没有。

这是编辑视图中常见的 Javascript/ajax:

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script>
        //Using this to scroll the page on the close of the modal/page refresh
         $(document).ready(function () {
            var JumpTo = '@ViewBag.JumpToDivId';
            if (JumpTo != "") {
                $(this).scrollTop($('#' + JumpTo).position().top);
            }
        });
        //Using this to Capture the click that opens the modals
        $('body').on('click', '.modal-link', function () {
            var actionUrl = $(this).attr('href');
            $.get(actionUrl).done(function (data) {
                $('body').find('.modal-content').html(data);
            });
            $(this).attr('data-target', '#modal-container');
            $(this).attr('data-toggle', 'modal');
        });
        //Using this to Capture the click that Submits the _EditFile,_DeleteFile,_CreateEdit forms on the modal
        $('body').on('click', '.relative', function (e) {
            e.preventDefault();
            var form = $(this).parents('.modal').find('form');
            var actionUrl = form.attr('action');
            var dataToSend = form.serialize();
            $.post(actionUrl, dataToSend).done(function (data) {
                $('body').find('.modal-content').html(data);
                var isValid = $('body').find('[name="IsValid"]').val() == 'True';
                var issueid = "";
                issueid = $('body').find('[name="issueidSaved"]').val();
                var jumpto = $('body').find('[name="jumpto"]').val();
                if (isValid) {
                    $('body').find('#modal-container').modal('hide');
                    if (issueid == "")
                    {
                        window.location.href = "/Issue/Edit/?id=" + issueid + "&jumpto=" + jumpto;
                    }
                }
            });
        })
        //Using this to Capture the click that Submits the _UploadFile form on the modal
        $(function () {
            $('body').on('click', '.fileupload', function (e) {
                e.preventDefault();
                var form = $(this).parents('.modal').find('form');
                var actionUrl = form.attr('action');

                var fdata = new FormData();
                $('input[name="file"]').each(function (a, b) {
                    var fileInput = $('input[name="file"]')[a];
                    if (fileInput.files.length > 0) {
                        var file = fileInput.files[0];
                        fdata.append("file", file);
                    }
                });
                $("form input[type='text']").each(function (x, y) {
                    fdata.append($(y).attr("name"), $(y).val());
                });
                $("form input[type='hidden']").each(function (x, y) {
                    fdata.append($(y).attr("name"), $(y).val());
                });
                $.ajax({
                    url: actionUrl,
                    method: "POST",
                    contentType: false,
                    processData: false,
                    data: fdata
                }).done((response, textStatus, xhr) => {
                    var isValid = $(response).find('[name="IsValid"]').val() == 'True';
                    var issueid = $(response).find('[name="issueidSaved"]').val();
                    var jumpto = $(response).find('[name="jumpto"]').val();
                    if (isValid) {
                        $('body').find('#modal-container').modal('hide');
                        window.location.href = "/Issue/Edit/?id=" + issueid + "&jumpto="+jumpto;
                    }
                   });
            })
        });

        $('body').on('click', '.close', function () {
            $('body').find('#modal-container').modal('hide');
        });

        $('#CancelModal').on('click', function () {
            return false;
        });

        $("form").submit(function () {
            if ($('form').valid()) {
                $("input").removeAttr("disabled");
            }
        });
    </script>

这里是 _DeleteFile Partial 视图和处理提交的 AttachmentController 代码:

<!--Modal Body Start-->

<div class="modal-content">
    <input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" />
    <input name="issueidSaved" type="hidden" value="@ViewBag.ID" />
    <input name="jumpto" type="hidden" value="@ViewBag.JumpToDivId" />
    <!--Modal Header Start-->
    <div class="modal-header">
        <h4 class="modal-title">Delete File</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <!--Modal Header End-->

    <form asp-action="DeletetheFile" asp-route-attachmentid="@ViewBag.id" asp-route-issueId="@ViewBag.issueId" asp-controller="Attachment" method="post" enctype="multipart/form-data">

        @Html.AntiForgeryToken()

        <div class="modal-body form-horizontal">
            Are you sure you want to delete the @ViewBag.title File?

            <!--Modal Footer Start-->
            <div class="modal-footer">
                <button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">No</button>
                <input type="submit" class="btn btn-success relative" id="btnSubmit" data-save="modal" value="Yes">
            </div>
            <div class="row">
                &nbsp;
            </div>

        </div> <!--Modal Footer End-->
    </form>

</div>
<script type="text/javascript">
    $(function () {

    });
</script>

<!--Modal Body End--> 

[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult DeletetheFile(int attachmentid, string issueId)
{
    string response = _adoSqlService.DeleteAttachment(attachmentid);
    ViewBag.ID = issueId;
    ViewBag.JumpToDivId = "upload";
    TempData["ID"]= issueId;
    TempData.Keep();
    return PartialView("_DeleteFile");
}

这是 _EditFile 部分视图和 AttachmentController 代码: 编辑文件 ×

    <form asp-action="EditFile" asp-controller="Attachment" method="post" enctype="multipart/form-data">

        @Html.AntiForgeryToken()

        <div class="modal-body form-horizontal">
            <input name="issueId" type="hidden" value="@ViewBag.issueId" />
            <input name="attachmentId" type="hidden" value="@ViewBag.attachmentId" />
            <label class="control-label">@ViewBag.aFileName</label><br />
            Make changes to description then select "Save Changes".<br />
            <input name="aIssueAttachmentDescription" class="form-control formtableborders" id="titletext" value="@ViewBag.aIssueAttachmentDescription" />

            <!--Modal Footer Start-->
            <div class="modal-footer">
                <button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">No</button>
                <input type="submit" class="btn btn-success relative" id="btnSubmit" data-save="modal" value="Save Changes">
            </div>
            <div class="row">
                &nbsp;
            </div>

        </div> <!--Modal Footer End-->
    </form>

</div>
<script type="text/javascript">
    $(function () {

    });
</script>

<!--Modal Body End-->  

[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult EditFile(IFormCollection collection)
{
    AttachmentModel model = new AttachmentModel();

    model.attachmentId = Convert.ToInt32(collection["attachmentId"]);
    model.aIssueAttachmentDescription = collection["aIssueAttachmentDescription"];
    string response = _adoSqlService.EditFileDescription(model);
    ViewBag.ID = collection["issueId"];
    ViewBag.JumpToDivId = "upload";
    TempData.Remove("ID");
    TempData["ID"] = collection["issueId"];
    TempData.Keep();
    return PartialView("_EditFile");
}

当我在 _DeleteFile 提交后在 Issue/Edit 操作中检查 TempData 时,它会显示以下内容(这是正确的):

当我在 _EditFile 提交后在 Issue/Edit 操作中检查 TempData 时,它显示以下内容(这是不正确的):

【问题讨论】:

  • 你只给我看临时数据,我无法理解你得到错误的步骤。以下是我的理解,你使用ajax重定向到DeletetheFile,在动作中,你可以得到正确的TempData。我不知道In the following action it is getting set properly (see the first image), but by the time it gets to the same action as the first one I showed it has changed (see second image).是什么意思。
  • @YiyiYou - 我试图进一步澄清这些问题。感谢您的帮助。

标签: c# asp.net-core


【解决方案1】:

你需要改变

TempData["ID"] = collection["issueId"];

TempData["ID"] = collection["issueId"].ToString();

因为collection["issueId"] 是类型Microsoft.Extensions.Primitives.StringValues 而不是类型String

这是显示类型的图片:

【讨论】:

  • 谢谢。我没想到。 Delete 使用的是字符串,而 Edit 使用的是 Collection。
猜你喜欢
  • 2021-04-04
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多