在我正在开发的系统中,我将一个带有多个选项的select发送到控制器中的字符串类型列表,现在我需要将从视图中获得的列表链接到我模型中的登录类列表。目标是字符串列表中的每个位置都成为新列表中的一个位置。
例如,我得到了以下列表,其中包含从视图select发送的值:
[0]=";147〃;
[1] =";33〃;
我需要将这个数组链接到我的另一个登录列表,类似于这个
登录[0]=";147
登录[1]=";33〃;
我会把我的代码和评论放在一起,以更好地解释它:
视图:
<select class="selectpicker" multiple data-live-search="true" asp-for="ListResponsibles">
<option value="147">John</option>
<option value="212">Maria</option>
<option value="33">Luiza</option>
</select>
型号:
//Here I get the options marked in the select
public List<string>ListResponsibles { get; set; }
//I want to pass the list I received from the view to this list
public List<Responsibles> ListResponsiblesData { get; set; }
public class Responsibles
{
public string Login { get; set; }
}
控制器:
public async Task<IActionResult> RegisterTask([FromForm] WebdeskTasks webdeskTasks)
{
//I created this variable to receive data from the other list
var LoginList = webdeskTasks.ListResponsiblesData;
//Here I tried to link each possibility of the view's list array to my list, but it doesn't show value in webdeskTarefas.ListResponsibles [i]
for (int i = 0; i < webdeskTasks.ListResponsibles.Count; i++)
{
LoginList[i].Login = webdeskTasks.ListResponsibles[i];
}
或LINQis方式:
public async Task<IActionResult> RegisterTask([FromForm] WebdeskTasks webdeskTasks)
{
webdeskTasks.ListResponsiblesData = webdeskTasks.ListResponsibles
.Select(entry => new Responsible { Login = entry })
.ToList();
//....
}
您可以尝试以下代码:
public async Task<IActionResult> RegisterTask([FromForm] WebdeskTasks webdeskTasks)
{
var LoginList = new List<Responsibles>();
foreach (string i in webdeskTasks.ListResponsibles)
{
Responsibles re = new Responsibles();
re.Login = i;
LoginList.Add(re);
}
webdeskTasks.ListResponsiblesData = LoginList;
//....
}