【问题标题】:How to delete a record in MVC without using a View?如何在不使用视图的情况下删除 MVC 中的记录?
【发布时间】:2015-07-24 16:08:55
【问题描述】:

通常我会在我的索引视图中添加以下内容:

@Html.ActionLink(" ", "Delete", new { id = item.UserId }, new { onclick = "return confirm('Are you sure you want to delete this user?');", @class = "delete-button" })

这使我可以在不离开我的列表的情况下删除表中的内联项目。我需要做的就是通过javascript确认确认删除。

我的动作是这样的:

public ActionResult Delete(int id)
{
    User user = db.Users.Find(id);
    if (user == null)
    {
        return HttpNotFound();
    }
    else
    {
        db.Users.Remove(user);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
}

我现在正在尝试同样的事情,但链接到我的网络服务,该服务将处理数据库上的删除。

唯一的区别在于控制器现在看起来像这样:

private async Task<ActionResult> Delete(int id)
{
    string url = String.Format("api/user/{0}", id);

    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:49474/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.DeleteAsync(url);

        return RedirectToAction("Index");
    }
}

为了彻底,这里是删除记录的网络服务代码:

public HttpResponseMessage Delete(int id)
{
    try
    {
        var existing = db.Users.Find(id);

        if (existing != null)
        {
            db.Users.Remove(existing);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

            return response;
        }
        else
        {
            throw new ArgumentNullException("Object ID not found");
        }

    }
    catch (Exception ex)
    {
        return ReportError(ex, "DELETE USER");
    }
}

这给了我 javascript 确认,但数据库上没有发生删除,我收到一个错误屏幕,显示不存在视图。

在调试时,我发现上面的功能甚至都没有被请求。我觉得我需要在控制器中添加一些东西,但我不确定是什么。

【问题讨论】:

  • 私有异步任务 Delete(int id) ...你的控制器的动作应该是公开的。
  • 执行此操作时,您如何不离开页面:return RedirectToAction("Index");
  • 还有一点,如果你用的是JS,redirectToAction("Index");不会工作。
  • @ThiagoCustodio 如果这是问题,我会用头撞到那边的墙上 -> |
  • @ThiagoCustodio 我刚刚撞到了一堵墙,就像我说的那样,因为问题似乎是我将删除功能声明为私有......谢谢,请回答你会得到虚假的互联网积分

标签: javascript c# asp.net-mvc


【解决方案1】:

只需将控制器的操作更改为公开:

public async Task<ActionResult> Delete(int id)
{
    string url = String.Format("api/user/{0}", id);

    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:49474/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.DeleteAsync(url);

        return RedirectToAction("Index");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2020-02-26
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多