通常我在索引视图中添加以下内容:
@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");
}
}
为了彻底,这是删除记录的Web服务代码:
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确认但是数据库上没有发生删除,我得到一个错误屏幕,显示没有视图存在。
调试后,我发现上面的函数甚至都没有请求。我觉得我需要在控制器中添加一些内容,但我不确定是什么。
答案 0 :(得分:0)
只需将控制器的操作更改为公开:
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");
}
}