1

ビューで作成した 2 つの異なるモデルにアクセスするためのビューモデルを作成したいと考えています。

このために、2 つの異なるモデルと、両方を含む 1 つのモデルを作成します。

私の問題は、私の見解ではデータにアクセスできないことです。

誰でもこれを手伝ってくれることを願っています。

私のビューで表現する必要があるのは次のとおりです。 Table1 : name title

表 2: 各画像の picpath

ここに私のコードがあります:

モデル 1:

 public class Table1
    {
        public int ID { get; set; }
        public string name{ get; set; }
        public string title { get; set; }
        public string edition{ get; set; }
        public string number{ get; set; }

    }

   public class DefaultConnection : DbContext
    {
        public DbSet<Table1> Res{ get; set; }
    }

モデル 2:

 public class Images
    {
        public SelectList ImageList { get; set; }   
        public int ID { get; set; }
        public string title{ get; set; }
        public string picpath { get; set; }

        public Img)
        {
            ImageList = GetImages();
        }

        public SelectList GetImages()
        {
            var list = new List<SelectListItem>();
            string connection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

            using (var con = new SqlConnection(connection))
            {
                con.Open();
                using (var command = new SqlCommand("SELECT * FROM Myimages", con))
                {
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        string title = reader[1] as string;
                        string imagePath = reader[2] as string;
                        list.Add(new SelectListItem() { Text = title, Value = imagePath });
                    }
                }
                con.Close();
            }
            return new SelectList(list, "Value", "Text");
        }

    }

私の見解 モデル:

 public class ViewModel
    {
        public Table1 table1{ get; set; }
        public Images xpto { get; set; }

        public ViewModel(Table1 table1)
        {
            Table1 = table1;
            xpto = new Images();
        }
    }



**Controller:**

 public ActionResult HotSpotMaker(int id = 0)
        {
            Table1 rev = db.Res.Find(id);          
            if (rev == null)
            {
                return HttpNotFound();
            }
//Here is something missing, have delete my version here because don´t make any sense
            return View(rev);
        }

意見:

  @model myproject.Models.ViewModel

注: 私はよく検索し、多くの人がこれを使用していることを発見しました: @model myproject.Web.Models.ViewModel ですが、この Web を選択できません。. これが関連しているかどうかはわかりませんが、おそらくそれを言うことが重要だと思いました.

4

2 に答える 2

1

まあ、それはかなり単純です、あなたViewは a を期待していますViewModel(ちなみに、それは悪い名前ですが、それは単なるテストだと思います)、しかしあなたはそれに を与えていTable1ます。

ViewModelオブジェクトからオブジェクトTable1を作成するメソッドが必要です

あなたの場合、コンストラクターをそのように呼び出すだけです

return View(new ViewModel(rev));
于 2013-08-02T13:48:50.397 に答える