【问题标题】:Trying to delete record from within a Details action尝试从详细信息操作中删除记录
【发布时间】:2013-09-15 14:47:54
【问题描述】:

我使用索引操作以网格状结构显示记录列表。我还有一个删除按钮作为允许用户删除特定行/记录的列之一。这很好用。我还在每一行中都有一个详细信息链接,以允许查看单个记录。

Delete 有自己的 HttpPost 操作。细节也有自己的规律动作。

问题是我现在想将此删除按钮代码添加到详细信息视图中,但我正在使用通知程序并且删除本身可以工作,但代码显示通知程序(因为详细信息中有一个记录==空检查行动)。我不知道如何解决这个问题。

代码如下:

public ActionResult Index()
{
    ...
    var myList = _repository.Table;
    // Nothing else relevant just displays list and sets up model
    return View(model);
}

public ActionResult Details(int id)
{
    ...
    var record = _repository.Get(id);

    // If I use the Delete action below then this will get called and fire;
    // I am trying to figure out how to avoid it firing when I use the Delete code
    // in the Details view (see .cshtml code below)
    if (record == null)
    {
    _myServices.Notifier.Warning
            (T("Request not found, please check the URL."));

        return RedirectToAction("Index");
    }

    var model = new myViewModel();
    model.Id = record.Id;
    // Pulling other records, nothing special

    return View(model);
}

[HttpPost]
public ActionResult Delete(int id, string returnUrl)
{
    ...
    var item = _repository.Get(id);
    if (item == null)
    {
        _myServices.Notifier.Error(T("Inquiry not found."));
    }
    else
    {
        _myServices.Notifier.Information(T("Request deleted successfully."));
        _repository.Delete(item);
    }

    return this.RedirectLocal(returnUrl, "~/");
}

我想知道是否应该创建一个单独的操作,例如 DeleteDetails,但是 Details 操作中的 record=null 检查仍然会触发。

这是索引视图和详细信息视图中的删除代码:

@{using (Html.BeginForm("Delete", "MyAdmin", 
    new { area = "MyNameSpace" }, 
    FormMethod.Post, new { @class = "delete-form" }))
    {
        @Html.AntiForgeryTokenOrchard()
        @Html.Hidden("id", Model.Id)
        @Html.Hidden("returnUrl", Context.Request.ToUrlString())
        <input type="submit" value="Delete" />
    }
}

也许我应该更改详细信息视图删除代码?

有什么想法吗?

【问题讨论】:

  • 因此您的Details 操作被触发,因为当您在详细信息视图中为returnUrl 传递Context.Request.ToUrlString() 时,您在Delete 操作中重定向到它。返回到您刚刚删除的记录的详细信息视图可能没有意义,因为您会遇到这样的错误。在这种情况下,我通常会重定向回列表。
  • @asymptoticFault 删除操作同时用于两个索引(它工作正常 - 所以在索引中你点击“删除”按钮,它返回到索引并显示它已被删除的消息并且它显示更新的列表,但没有删除它的记录)和详细信息操作。但是,我使用“详细信息中的删除”操作一起破解,所以你是对的,我犯了一个错误。对不起,我不是程序员。我应该创建一个特定于详细信息的新删除操作吗?你能提供一个带有代码的答案吗?还是我应该修改现有代码来解决这个问题?
  • 当您从详细信息操作中删除时重定向回索引如何?只需将delete-form 中隐藏的returnUrl 的值更改为Url.Action("Index")
  • 鉴于您的详细信息操作将在记录不存在时重定向到索引,因此在删除记录时执行此操作是有意义的。

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

所以您的Details 操作被触发,因为当您在Details 视图中为returnUrl 传递Context.Request.ToUrlString() 时,您在Delete 操作中重定向到它。回到 Details 视图查看您刚刚删除的记录可能没有意义,因为您会遇到这样的错误。

当您从Details 操作Delete 时重定向回Index 怎么样?只需将delete-form 中隐藏的returnUrl 的值更改为Url.Action("Index")。鉴于您的 Details 操作将在记录不存在时重定向到 Index,因此在删除记录时执行此操作是有意义的。

【讨论】:

    猜你喜欢
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    相关资源
    最近更新 更多