我需要在 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>
也許我解釋得不好。我想從數字串列中創建一個陣列。該陣列必須在表格的每一行中重復,并且用戶從該串列中為表格的每一行選擇一個值。現在我的問題是我不知道如何創建這個陣列以便我可以使用它的名稱,下一個問題是我不知道如何獲取代碼的值。請記住,對于表格的每一行,這個數字串列都是重復的,我在代碼端都需要它們。
uj5u.com熱心網友回復:
實際上,理解您的需求有些困難。但是從你的問題和代碼來看,我猜你想用它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>
演示:
![如何獲取 SelectListItem[] 的值](https://img.uj5u.com/2022/06/14/619bb2d4c81746a38e43f4eb098e28d6.gif)
然后你可以看到它得到了你成功選擇的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490304.html
