[英]ASP.NET Mvc InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' Error
I am making a page.我正在制作一个页面。 I am trying to make a DropDownList
on this page.我正在尝试在此页面上创建一个DropDownList
。 There should be two items in this DropDownList
.这个DropDownList
应该有两个项目。 I am trying to determine these two items through the Controller.我正在尝试通过 Controller 确定这两项。
But I am getting an error like this:但我收到这样的错误:
My codes:我的代码:
Index.cshtml
: Index.cshtml
:
@model IncomeAndExpensiveWeb.Models.IncomeExpensiveTable
@{
ViewData["Title"] = "Money";
}
<div class="p-3 mb-2 bg-dark text-white">Add</div>
<form class="form-control" action="IncomeExpensiveTables/AddRecord" method="post">
<div class="row">
<div class="col">
<div class="mb-3">
<label for="Name" class="form-label">Name:</label>
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
</div>
</div>
<div class="col">
<div class="mb-3">
<label for="Surname" class="form-label">Surname:</label>
@Html.TextBoxFor(m => m.Surname, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<label>
<select class="form-control">
@foreach (var item in (IEnumerable<IncomeExpensiveTable>)ViewBag.MoneyStatusList)
{
<option value="@item.Id">@item.MoneyStatus</option>
}
</select>
</label>
</div>
<div class="form-group">
<label>Image:</label>
<input type="File" name="UploadedImage"/>
</div>
<br/>
<div>
<button class="btn btn-success">Add</button>
</div>
</div>
</form>
Controller: Controller:
[HttpGet]
public ActionResult Index()
{
List<string> MoneyStatusList = new List<string>();
MoneyStatusList.Add("Income");
MoneyStatusList.Add("Expensive");
ViewBag.MoneyStatusList = MoneyStatusList;
return View("Index");
}
Why could this be?为什么会这样? How can I solve it?我该如何解决? Thanks for help.感谢帮助。
select class="form-control">
@foreach (var item in (IEnumerable<IncomeExpensiveTable>)ViewBag.MoneyStatusList)
{
<option value="@item.Id">@item.MoneyStatus</option>
}
"IncomeExpensiveTable" is string on code behind. “IncomeExpensiveTable”是后面代码的字符串。 Thats why you can't cast.这就是为什么你不能投。
You have to cast it your ViewBag model type which is List() and only use just item there is no any item.Id or item.MoneyStatus.您必须将其转换为您的 ViewBag model 类型,即 List() 并且仅使用 item,没有任何 item.Id 或 item.MoneyStatus。
Like this:像这样:
<select class="form-control">
@foreach (var item in (List<string>)ViewBag.MoneyStatusList)
{
<option value="@item">@item</option>
}
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.