繁体   English   中英

ASP.Net Core Web App - cshtml 文件无法调用 Controller 方法

[英]ASP.Net Core Web App - cshtml file can't invoke Controller method

试图从我的 index.cshtml 文件中调用我的 controller 上的方法。

Html.BeginForm("Index", "Default", FormMethod.Get);

其中 index 是我的方法名称,默认是 controller 并且 get 是不言自明的。 当我右键单击“索引”和 go 来实现时,它会将我带到我的 controller 中的方法。 但是,当我调试代码时,它不会进入 Controller 方法并转到下一行代码,尽管断点显然已经到位并且调试工具选项设置正确。

也试过

<form method="get" action='@Url.Action("Index", "Default")'></form>

同样不能步入controller。

如何正确调用我的 controller 方法?

形式

HTML <form>在调用 controller 操作之前需要一个提交按钮(通常是一些控件)。 看起来您示例中的表单是空的。

您尚未显示 controller,但假设您想将字符串传递给 controller 操作,可能是搜索或过滤:

public ActionResult Index(string searchTerm)
{
    // do something with parameters then return view
    return View();
}

在您看来,而不是这样:

Html.BeginForm("Index", "Default", FormMethod.Get);    // empty form

它应该是这样的:

@Html.BeginForm("Index", "Default", FormMethod.Get) 
{
    // add controls here, what parameters are you passing? 
    @Html.TextBox("SearchTerm")
    <input type="submit" value="Search" />
}

标签助手

由于您使用的是 ASP.Net-Core,因此您可以利用标签助手,它允许您以更像 HTML 的方式编写代码。 我鼓励您阅读ASP.NET Core 中 forms 中的 Tag Helpers 使用标签助手编写上述内容的一种方法是:

<form asp-action="Index" asp-controller="Default" method="get">
    <input type="text" name="SearchTerm" />
    <button>Search</button>
</form>

行动链接

也许您想创建指向Default/Index的超链接? 在这种情况下,请使用@Html.ActionLink帮助器:

@Html.ActionLink("go to this link", "Index", "Default")

这将创建一个常规锚<a>

<a href="/Default">go to this link</a>

标签助手版本

<a asp-action="Index" asp-controller="Default" >Click this link</a>

当您加载 index.cshtml 时,默认会进入索引操作。您需要在索引操作中返回 model。

这是一个简单的演示,如下所示:

1.Model:

public class Test
{
    public int ID { get; set; }
    public string Title { get; set; }
}

2.Index.cshtml:

@model IEnumerable<TestModel>
<h1>Index</h1>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>            
        </tr>
}
    </tbody>
</table>

3.索引动作:

public class TestModelsController : Controller
{
    private readonly MyDbContext _context;

    public TestModelsController(MyDbContext context)
    {
        _context = context;
    }

    // GET: TestModels
    public async Task<IActionResult> Index()
    {
        var model = await _context.TestModel.ToListAsync();
        return View(model);
    }
}

参考: 将数据传递给视图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM