我需要在 asp.net 核心中使用一个名称获取许多选择列表的值
我使用循环填写表格并显示它。问题是,在表格的每一行中,选择列表中都有一系列项目,这些项目具有为表格的每一行填充的固定值。
接下来是发布页面时,我需要知道用户从选择列表项的每一行中选择了什么值
这意味着我需要表格行号和选择的值。
主要问题是这些选择列表也是名称,我不能为每个项目命名,因为我收回时没有其他名称
感谢您告诉我如何解决此问题
<tbody>
@foreach (var item in allQuestion)
{
<tr>
<td>@item.Question_Title</td>
<td>@item.Answere1</td>
<td>@item.Question_type</td>
<td>
<select id="trueRate[@item.Question_ID]" class="form-control">
@foreach (var rate in TrueRate)
{
<option value="@rate.Value">@rate.Text</option>
}
</select>
</td>
</tr>
}
</tbody>
也许我解释得不好。我想从数字列表中创建一个数组。该数组必须在表格的每一行中重复,并且用户从该列表中为表格的每一行选择一个值。现在我的问题是我不知道如何创建这个数组以便我可以使用它的名称,下一个问题是我不知道如何获取代码的值。请记住,对于表格的每一行,这个数字列表都是重复的,我在代码端都需要它们。
实际上,理解您的需求有些困难。但是从你的问题和代码来看,我猜你想用它foreach()
来遍历你的模型,然后在每个项目中,你想嵌套一个下拉列表,所以我在这里写了一个简单的演示,希望它是你想要的。
模型
public class Question
{
public int Id { get; set; }
public string QuestionName { get; set; }
public string QuestionType { get; set; }
public string answers { get; set; }
}
public class Answer
{
public string Text { get; set; }
public float Value { get; set; }
}
控制器
public IActionResult Create()
{
//For testing convenience, I just hard code here
List<Question> questions = new List<Question>()
{
new Question{
Id = 1,
QuestionName = "Question1",
QuestionType = "TypeA",
},
new Question{
Id = 2,
QuestionName = "Question2",
QuestionType = "TypeB",
},
new Question{
Id = 3,
QuestionName = "Question3",
QuestionType = "TypeC",
},new Question{
Id = 4,
QuestionName = "Question4",
QuestionType = "TypeD",
},
new Question{
Id = 5,
QuestionName = "Question5",
QuestionType = "TypeE",
}
};
List<Answer> answers = new List<Answer>()
{
new Answer{
Text = "AAAA",
Value = 0.2F
},
new Answer{
Text = "BBBB",
Value = 0.3F
},
new Answer{
Text = "CCCC",
Value = 0.4F
},
new Answer{
Text = "DDDD",
Value = 0.5F
}
};
List<SelectListItem> model = new List<SelectListItem>();
foreach(var item in answers)
{
model.Add(new SelectListItem() { Text = item.Text,Value = item.Value.ToString()});
}
ViewBag.drop = model;
return View(questions);
}
[HttpPost]
public IActionResult Create(List<Question> model)
{
float result=0;
foreach (var item in model)
{
float data = float.Parse(item.answers);
result += data;
}
//........
}
看法
@model List<Question>
@{
var i = 0;
}
<form method="post">
<table border="1">
<tbody>
@foreach (var item in @Model)
{
<tr >
<td>
@item.Id
<input type="hidden" asp-for="@Model[i].Id">
</td>
<td>
@item.QuestionName
<input type="hidden" asp-for="@Model[i].QuestionName">
</td>
<td>
@item.QuestionType
<input type="hidden" asp-for="@Model[i].QuestionType">
</td>
<td>
<select asp-for="@Model[i].answers" asp-items="@ViewBag.drop" class="form-control"></select>
</td>
</tr>
i++;
}
</tbody>
</table>
<button type="submit">submit</button>
</form>
演示:
然后你可以看到它得到了你成功选择的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句