首页 > 解决方案 > C# MVC 控制器方法未填充视图中的项目

问题描述

C#新手在这里。

检查了“在视图控制器之间传递数据”,但它有很多我目前不熟悉的语法。计划稍后进行更多研究——例如协议和委托设计。

Root:制作一个 ASP.NET 应用程序。视图中的 foreach 填充列表中的项目无法填充到主控制器中:

查看语法

<input type="text" id="deviceId"/>
@Html.ActionLink("Add Device", "Add", new { /*id=item.PrimaryKey*/})
<table class="table">
    <thead>
        <tr>
            <th>Include</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.include)
        {
            <tr>
                <td>
                    <p>@Html.DisplayFor(m => item)</p> |
                    @Html.ActionLink("Exclude", "Exclude", new { /*id=item.PrimaryKey*/ }) |
                   ==> <a asp-controller="Home" asp-action="Delete" asp-route-id="@item" class="btn btn-danger">Delete</a> 
                </td>
            </tr>
        }
    </tbody>
</table>

<table class="table">
    <thead>
        <tr>Exclude</tr>
    </thead>
    <tbody>
        @foreach (var item in Model.exclude)
        {
            <tr>
                <td>
                    <p>@Html.DisplayFor(m => item)</p> |
                    @Html.ActionLink("Include", "Include", new { /* id=item.PrimaryKey */ }) |
                    @Html.ActionLink("Delete", "Delete", new {  })
                </td>
            </tr>
        }
    </tbody>
</table>

控制器删除方法

  public IActionResult Delete(==>string id)
        {
            var theList = DeviceDictionaryConversion.DevDictionaryDEV();

            theList.include.Remove(id);

            return View("ListModDev", theList);
        }

检查这是否是视图中对象的正确数据类型,或者我在这里可能无法完全理解的其他想法。同样,来自示例运行的断点显示控制器“删除”方法中的代码执行。

标签: c#model-view-controllerviewcontrollervisual-studio-2019

解决方案


好吧,我不认为这==>是正确的语法....或任何类型的语法都适合这种情况。

二:在这里你是说当它被“点击”时

@Html.ActionLink("Delete", "Delete", new {  })

调用Delete方法。但是Delete期待一个id您没有提供的参数。new { }如果你没有通过任何东西,那么这样做也是没有意义的。

但是,如果您希望此方法接受参数以及不接受参数,则可以为参数分配一个值,例如:

 public IActionResult Delete(string id = "")    // Set to empty string

而不是<a asp-controller="Home" asp-action="Delete" asp-route-id="@item" class="btn btn-danger">Delete</a>您尝试使用@Url.Action()? 我发现这要简单得多,因为您需要做的就是:

@Url.Action("Delete", "Home", new {id = @item})    // Assuming that `@item` is a string

IE

<a href="@Url.Action("Delete", "Home", new {id = @item})" class="btn btn-danger">

推荐阅读