0

私はASP.NETを初めて使用しますが、Java でのプログラミングは少し知っています。郵便番号を使用して文字列を返すデータベースをクエリし、その文字列を使用して別のデータベースをクエリしたいと考えています。同じ制御モデルでこれを行いたかったのです。簡単だろうと思っていたのですが、かなり簡単そうです。

コントローラーを作成したときに、最初のデータベースのモデル クラスを配置しました。これまでのところ、最初のデータベースのクエリまでは完了しましたが、DBEntities を介して 2 番目のデータベースにクエリを実行する文字列が得られました。 .

これにより、次のエラーが表示されます。

> The model item passed into the dictionary is of type
> 'System.Collections.Generic.List`1[FinalBallot.Models.AgainCandidate]',
> but this dictionary requires a model item of type
> 'System.Collections.Generic.IEnumerable`1[FinalBallot.Models.ZipTable]'.

これを簡単に解決する方法はありますか?

public class Default1Controller : Controller
{
    private CandidatesDBEntities db = new CandidatesDBEntities();

    public string districString = "";
    //
    // GET: /Default1/

    public ViewResult Index(string searchString)
    {
        var queryZip = from s in db.ZipTables select s;
        var queryCandidates = from s1 in db.AgainCandidates select s1;
        double sT = 0;

        //method so it doesnt display the whole db
        if (String.IsNullOrEmpty(searchString))
        {
            queryZip = queryZip.Where(s => s.ZipL.Equals(0));
        }

        if (!String.IsNullOrEmpty(searchString))
        {
            sT = double.Parse(searchString);
            queryZip = queryZip.Where(s => s.ZipL.Equals(sT));

            try
            {
                districString = queryZip.ToList().ElementAt(0).District;
            }
            catch
            {
            }

            if (!String.IsNullOrEmpty(districString))
            {
                queryCandidates = queryCandidates.Where(s1 => s1.District.Equals(districString));
            }
        }
        return View(queryCandidates.ToList());
    }
4

1 に答える 1

0

あなたの見解では、モデルを次のように指定しましたIEnumerable<ZipTable>か? ビューに渡すモデルはIEnumerable<AgainCandidate>であるため、モデルを別のものとして指定するとエラーが発生します。ビューのモデルを に変更する必要がありますIEnumerable<AgainCandidate>

更新:改訂された説明に基づいて、いくつかのことができます:1)ページに表示するコレクションごとに2つのプロパティを持つ「ViewModel」を次のように作成します。

public class MyViewModel
{
    IEnumerable<ZipTable> Zips { get; set; }
    IEnumerable<AgainCandidate> Candidates { get; set; }
}

それをアクション メソッドでインスタンス化し、それをモデルとして返します。これは私の好ましいアプローチです。

2) アクション メソッドの ViewData バッグに 2 つのコレクションを隠します。

ViewData["Zips"] = queryZip.ToList();
ViewData["Candidates"] = queryCandidates.ToList();

return View(ViewData);

次のように、ビューでこのデータを取得できます。

@foreach (var zip in ViewData["Zips"] as IEnumerable<ZipTable>) 
{
    ...
}
于 2012-10-12T18:49:57.953 に答える