【问题标题】:How to submit form in MVC如何在 MVC 中提交表单
【发布时间】:2016-07-14 04:16:12
【问题描述】:

我在下面的视图中有代码:

@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,并且消息错误:

未找到视图“DeleteItem”或其主视图,或者没有视图引擎支持搜索到的位置

【问题讨论】:

  • 这个方法 DeleteItem 在测试控制器中吗?
  • @SmitPatel : DeleteItem 是 TestController 中的操作
  • return View(); 表示您在TestController 中返回名为DeleteItem.cshtml 的视图。如果要返回不同的视图,则需要指定其名称 - return View("MyOtherView");
  • 真正的问题是你为什么要在删除项目后返回视图(这没有意义,因为项目不再存在。你应该使用return RedirectToAction(....) 重定向到另一个视图。
  • 如果您想重定向到名称与您的ActionName 不同的视图,请在return view("ViewName") 中指定您的Viewname,在我的回答中查看更多信息。

标签: asp.net-mvc form-submit


【解决方案1】:

这件事的发生是因为你没有在

中指定你的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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    相关资源
    最近更新 更多