0

ASP.Net MVC 4

ドロップダウンリストに国のリスト (DB の Country テーブルのデータ) を入力しようとしています。次のエラーが表示されます。

The model item passed into the dictionary is of type 
System.Collections.Generic.List`1[System.Int32]', but this dictionary requires a model    item of type 'BIReport.Models.Country'.  

ASP.Net MVC は初めてで、そのエラーがわかりません。私が感じているのは、Index メソッドが返すものは、View で使用しているモデルと一致しないということです。

モデル::

namespace BIReport.Models
{
  public partial class Country
  {
    public int Country_ID { get; set; }
    public string Country_Name { get; set; }
    public string Country_Code { get; set; }
    public string Country_Acronym { get; set; }
  }

 }

コントローラ::

   public class HomeController : Controller
{
    private CorpCostEntities _context;

    public HomeController()
    {
        _context = new CorpCostEntities();
    }

    //
    // GET: /Home/

    public ActionResult Index()
    {
        var countries = _context.Countries.Select(arg => arg.Country_ID).ToList();
        ViewData["Country_ID"] = new SelectList(countries);
        return View(countries);
    }

}

意見::

@model BIReport.Models.Country
<label>
Country @Html.DropDownListFor(model => model.Country_ID, ViewData["Country_ID"] as SelectList)
</label>

どこが間違っていますか?

4

3 に答える 3

0

問題はビューの 1 行目にあります。次のように変更します。

@model IEnumerable<BIReport.Models.Country>

また、すでにモデルをビューに渡している場合は、モデルを渡す必要はありません:

ViewData["Country_ID"] = new SelectList(countries);
于 2012-12-04T10:14:56.253 に答える
0

CountryID を選択しているため、整数のリストがビューに渡されます。

私はあなたが本当にこのようなものが欲しいと思います:

public ActionResult Index()
{
    var countries = _context.Countries.ToList();
    ViewData["Country_ID"] = new SelectList(countries, "Country_ID", "Country_Name");
    return View();
}

なぜあなたの見解のモデルとして単一の国を持っているのか、私にはよくわかりません。

アップデート:

モデルが国である理由はまだわかりません。選択した国の ID を投稿するだけであれば、モデルはまったく必要ありません (または単に整数を持っているだけです)。ただし、これは問題ありません。

意見

@model MvcApplication1.Models.Country

@Html.DropDownListFor(m => m.Country_ID, ViewData["Country_ID"] as SelectList)
于 2012-12-04T10:16:45.280 に答える