【问题标题】:How to add a value to a class if the class contains LIST<class>如果类包含 LIST<class>,如何向类添加值
【发布时间】:2018-07-21 15:57:58
【问题描述】:

我有一个班级。

public class Graf
    {
        public List<Point> first { get; set; }
        public List<Point> second { get; set; }
}

这个类包含列表

public class Point
    {
        public int x { get; set; }
        public int y { get; set; }


        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    } 

我需要在 index.cshtml 中的 Graf 类中添加一个 Point:

@model WebApplication2.Models.Graf
<table>
        <tr>
            <td></td>
            <td>
                <div class="item">
                    <label>Y</label>
                    <input name="Y11" value="@Model.first" />  --------??
                </div>
            </td>
        </tr>
</table>
    <input type="submit" value="Send" />

但我现在不知道如何输入 Graf 类点?

我该怎么做?

【问题讨论】:

  • 您只需将对象从客户端传递到控制器,然后将此对象添加到您的列表中:first.Add(point)
  • 好的,我有在控制器中添加点的方法,但是如何从客户端调用此方法?例如,我有 以及我必须如何从 index.csHtml 中放置类 Point。谢谢!

标签: asp.net visual-studio razor asp.net-core-mvc


【解决方案1】:

好的。因此,让我们从客户端代码开始。我假设您有下一个 Index.cshtml 视图。

    <!-- You use this code to display data from your model -->
<table>
        <tr>
            <td></td>
            <td>
                <div class="item">
                    <label>Y</label>
                    <input name="Y11" value="@Model.first" />  --------??
                </div>
            </td>
        </tr>
</table>

您需要一个将新 Point 对象从您的视图发布到控制器的代码。它可能是这样的:

<form asp-controller="Home" asp-action="InsertPoint" method="post">
    X value: <input type="text" name="x"><br>
    Y value: <input type="text" name="y"><br>
    <input type="submit" value="Submit">
</form>

在您的控制器中,您应该使用以下签名创建操作

[HttpPost]
public async Task<IActionResult> InsertPoint(Point point)
{
    //Validation and insertion to list
    return View();
}

注意

这不是一个理想的解决方案。您可以通过许多不同的方式执行此任务。我的目的只是向您展示如何做到这一点的基本想法。如果您需要更多信息,可以从article开始

当然,请记住,谷歌是你的好朋友。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多