我想创建一个 View 模型以在我的 View 中访问我创建的两个不同模型。
为此,我创建了两个不同的模型和一个我同时包含两者的模型。
我的问题是在我看来我无法访问数据。
希望有人能对此提供帮助。
在我看来我需要表达的是: 表格1 : 姓名 标题
表 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");
}
}
我的 View 模型:
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 ,但我无法选择这个网站。 .我不知道这是否相关,我想说出来也许很重要。
请您参考如下方法:
您将 Table1 作为 View 模型传入,但这不是您的 View 模型。
尝试:
return View(new Models.ViewModel(rev));
