Home > Net >  ASP.NET Mvc InvalidCastException: Unable to cast object of type 'System.Collections.Generic.Lis
ASP.NET Mvc InvalidCastException: Unable to cast object of type 'System.Collections.Generic.Lis

Time:08-09

I am making a page. I am trying to make a DropDownList on this page. There should be two items in this DropDownList. I am trying to determine these two items through the Controller.

But I am getting an error like this:

enter image description here

My codes:

Index.cshtml:

@model IncomeAndExpensiveWeb.Models.IncomeExpensiveTable
@{
    ViewData["Title"] = "Money";
}

<div >Add</div>
<form  action="IncomeExpensiveTables/AddRecord" method="post">
    <div >
        <div >
            <div >
                <label for="Name" >Name:</label>
                @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
            </div>
        </div>
        <div >
            <div >
                <label for="Surname" >Surname:</label>
                @Html.TextBoxFor(m => m.Surname, new { @class = "form-control" })
            </div>
        </div>
        <div >
            <label>
                <select >
                    @foreach (var item in (IEnumerable<IncomeExpensiveTable>)ViewBag.MoneyStatusList)
                    {
                        <option value="@item.Id">@item.MoneyStatus</option>
                    }
                </select>
            </label>
        </div>  
        <div >
            <label>Image:</label>
            <input type="File" name="UploadedImage"/>
        </div>
        <br/>
        <div>
            <button >Add</button>
        </div>
    </div>
</form>

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.

CodePudding user response:

select >
                    @foreach (var item in (IEnumerable<IncomeExpensiveTable>)ViewBag.MoneyStatusList)
                    {
                        <option value="@item.Id">@item.MoneyStatus</option>
                    }

"IncomeExpensiveTable" is string on code behind. Thats why you can't cast.

CodePudding user response:

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.

Like this:

 <select >
                @foreach (var item in (List<string>)ViewBag.MoneyStatusList)
                {
                    <option value="@item">@item</option>
                }
  </select>
  • Related