MVC中如何提交表单

How to submit form in MVC

我有以下视图的代码:

@using (@Html.BeginForm("DeleteItem", "Test", new { id = 3 }, FormMethod.Post, new { @class = "form" }))
{
  @Html.AntiForgeryToken()
  <a class="submit-process" href="javascript:void(0);"><i class="fa fa-trash-o"></i> Delete</a>
}

脚本代码:

$('.submit-process').click(function () {
    if (confirm('You want delete?')) {
        $(this).closest("form").submit();
    }
    else return false;
});

控制器测试中的动作如下:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteItem(int id)
    {
        return View();
    }

当我点击提交时,它没有找到操作 DeleteItem,并且消息错误:

The view 'DeleteItem' or its master was not found or no view engine supports the searched locations

发生这种情况是因为您没有在

中指定您的viewName
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteItem(int id)
{
    return view('YOUR VIEW NAME');
}

而你的例子可能会出现这种类型的错误。

The view 'DeleteItem' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Test/DeleteItem.aspx
~/Views/Test/DeleteItem.ascx
~/Views/Shared/DeleteItem.aspx
~/Views/Shared/DeleteItem.ascx
~/Views/Test/DeleteItem.cshtml
~/Views/Test/DeleteItem.vbhtml
~/Views/Shared/DeleteItem.cshtml
~/Views/Shared/DeleteItem.vbhtml

当你在return view()中没有设置viewname时,会自动将方法名作为viewname并尝试在上述位置找到它。

多看Here

详细了解 Controllers and Action Methods in ASP.NET MVC Applications.