ASP.Net如何在不重定向视图的情况下调用控制器中的方法



我有一个视图,显示指定文件夹中的每个文件和名称旁边的删除按钮。我希望用户能够点击按钮,从文件夹中删除文件,然后用更新后的文件列表刷新页面。

Index.cshtml


@{
ViewBag.Title = "Index";
}
@{
var arrayOfDocs = ViewData["arrayOfDocs"] as string[];
}
<h2>Case Log Documents</h2>
<table class="table">
<tr>
<th>
Files
</th>
<th></th>
</tr>
@foreach (var item in arrayOfDocs)
{
<tr>
<td>
<a href="~/Case_Log_Docs/@item">@item</a>
</td>
<td>
@Html.ActionLink("Delete", "Delete", new { fileName = item })
</td>
</tr>
}
</table>

有了这行,我试图在我的控制器@Html.ActionLink("Delete", "Delete", new { fileName = item })中调用Delete方法。然而,动作链接将我重定向到一个删除页面(它不存在,也永远不会存在)。我想要发生的是调用'Delete'方法,然后刷新我所在的页面。

控制器

[HttpPost]
public ActionResult Delete(string fileName)
{
try
{
string path = Server.MapPath("~/Case_Log_Docs/");
string fullPath = path + fileName;
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
return RedirectToAction("Index");
}
catch
{
return View("Index");
}
}

我如何设置这个来做那个?

听起来好像没有找到路线。你有几件事要做。

首先,使用POST动词将方法标记为接受Http请求:
[HttpPost]
public ActionResult Delete(string fileName)

这意味着来自前端的请求需要使用POST作为谓词,以便正确路由。正如@jackdraw在他的回答中提到的,您需要使用表单来完成此操作。或者,您可以做一个Ajax帖子,但该选项似乎超出了您的问题范围,所以用表单标记将表括起来。您没有提供控制器的名称,所以我将使用占位符:

@using (Html.BeginForm("Delete", "NameOfControllerWithDeleteMethod"))
{
//Put your table here
}

您还需要一个字段来保存要删除的内容的标识符。在本例中,文件名本身:

@using (Html.BeginForm("Delete", "NameOfControllerWithDeleteMethod"))
{
<input type="hidden" id="fileName" name="fileName" />
//Put your table here
}

然后需要用要删除的文件的名称填充此字段。您可以在Delete按钮的Click事件上执行此操作。将操作链接替换为类型为submit的输入,并使用JS对其进行设置。在你的循环里。注意JS字符串和Razor代码的插值:

@foreach (var item in arrayOfDocs)
{
<tr>
<td>
<a href="~/Case_Log_Docs/@item">@item</a>
</td>
<td>
<input type="submit" value="Delete File" onclick="document.getElementById('fileName').value = '@item';" />
</td>
</tr>
}

最后,在控制器的Delete方法上,无论您是否遇到错误,您都希望在这两种情况下重定向回原始Index方法。您可以使用临时数据收集来传回只显示一次的消息:

try
{
string path = Server.MapPath("~/Case_Log_Docs/");
string fullPath = path + fileName;
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
TempData["UserMessage"] = "Success!";
return RedirectToAction("Index", "NameOfControllerWithIndexMethod");
}
catch
{
TempData["UserMessage"] = "Something went wrong... :-(";
return RedirectToAction("NameOfControllerWithIndexMethod");
}

在视图中收集这些数据并在某处显示:

@{ var userMessage = TempData["UserMessage"] as string; }
@if(!string.IsNullOrWhiteSpace(userMessage))
{
<div class="some-message-style">@userMessage</div>
}

最新更新