如何将输入的所选行的所有文本传递给动作?

时间:2019-06-19 06:11:40

标签: asp.net-core asp.net-core-mvc model-binding

我的项目中有此视图。

我想在所选的每一行中获取输入文本。

如何将输入的所选行的所有文本传递给动作

<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
    <thead>
        <tr>
            <th width="45%">Select</th>
            <th width="45%">User Name</th>
            <th width="5%">Description</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.TypeList)
        {
            <tr>
                <td>
                    <input type="checkbox" name=checklist" id="checklist"/>
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.UserName)
                </td>
                <td>
                    <input type="text" name="Extradecription"/>
                </td>
            </tr>
        }
    </tbody>

我的动作。如何为选定的行获取相应的文本和复选框值

    public IActionResult Index()
    {
        return View(repository.GetUser());
    }


    public IActionResult Save(int[] checklist,string[] Extradecription)
    {
        repository.Save(checklist,Extradecription);
        return View(repository.GetUser());
    }

1 个答案:

答案 0 :(得分:1)

如果您尝试获取控制器操作代码中显示的两个不同的数组,则未选择项的文本会出现问题,复选框的数组将按预期方式绑定,但说明会有所不同,只是为了清楚起见,请检查以下示例:

假设我们有一个带有树选项的列表:

  • 100-Foo
  • 200-酒吧
  • 300-扎兹

如果我们为项目设置以下选择:

  • Foo,一个
  • Zaz,c

如果我们查看请求,这是原始请求:

checklist = 100,300
Extradecription = a,null,c

因此,麻烦是避免为未选择的选项绑定空描述,这很复杂,在这种情况下,我建议您采用明确的解决方案:

  1. 创建模型以创建实体流程
  2. 为选项创建模型
  3. 在创建实体模型中添加选项模型列表
  4. 初始化模型以创建新实体
  5. 使用asp-for标签在视图中呈现输入
  6. 检索创建新实体的请求

我将使用模型和属性的名称来说明如何在您的请求中绑定类型化数组,并根据您的情况更改名称。

创建实体模型:

public class CreateEntity
{
    public CreateEntity()
    {
        Items = new List<SelectedItem>();
    }

    // Step 3
    [BindProperty]
    public List<SelectedItem> Items { get; set; }

    // Another properties
}

选项模型:

public class SelectedItem
{
    public bool IsSelected { get; set; }

    public int Code { get; set; }

    public string Name { get; set; }

    public string Desc { get; set; }
}

呈现选项列表:

@for (var i = 0; i < Model.Items.Count; i++)
{
    <input asp-for="@Model.Items[i].IsSelected" />@Model.Items[i].Name
    <input asp-for="@Model.Items[i].Desc" />
    <br/>
}

控制器中的GET和POST操作:

[HttpGet]
public IActionResult CreateOption()
{
    // Set the items list
    var model = new CreateEntity
    {
        Items = new List<SelectedItem>
        {
            new SelectedItem{ Code = 100, Name = "Foo" },
            new SelectedItem{ Code = 200, Name = "Bar" },
            new SelectedItem{ Code = 300, Name = "Zaz" }
        }
    };

    return View(model);
}

[HttpPost]
public IActionResult CreateOption(CreateEntity form)
{
    // Retrieve only selected items
    var query = form.Items.Where(item => item.IsSelected == true).ToList();

    return View();
}

如果您想进一步了解Razor页面中的复选框,请检查以下链接:Checkboxes in a Razor Pages Form

请让我知道这个答案是否有用。

相关问题