如何在MVC中绑定自定义模型类 [英] How to bind custom model class in mvc
问题描述
我是MVC的新手.我正在一个项目中,在该项目中我创建了一个模型类和上下文类,如果我以普通视图查看记录,则该类很好地工作. 但是,如果我尝试按"Series_Name"分组获取数据,并将其绑定到同一模型类中,则会出现错误.这是我的代码
I am new in MVC. I am working on a project where i have created a model class and also context class which is working good if i view the record in normal view. but if i try to get the data in group by "Series_Name" and bind it into same model class it gives error. here is my code
这是Model类和DBContextClass
Here is Model class and DBContextClass
[Table("tblvideo")]
public class TVSerial
{
[Key]
public Int64 Video_ID { get; set; }
public string Series_Name { get; set; }
public string Season_No { get; set; }
public string Episode_No { get; set; }
public string Episode_Name { get; set; }
public string Time_Duration { get; set; }
public string File_Url_480p { get; set; }
public string File_Url_720p { get; set; }
public string Description { get; set; }
public bool Is_Active { get; set; }
public string Image_Url_Small { get; set; }
public string Image_Url_Big { get; set; }
}
public class TvSerialContext : DbContext
{
public DbSet<TVSerial> TvSerials { get; set; }
}
这是控制器类:
public class TvSerialController : Controller
{
public ActionResult ListAllTvSerial()
{
try
{
TvSerialContext tvContext = new TvSerialContext();
List<TVSerial> tv = tvContext.TvSerials.ToList();
return View(tv);
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
}
上面的代码按预期工作,但是如果我这样做:
Above code works as expected, but if i am doing this :
public ActionResult ListAllSeason(string serial)
{
try
{
TvSerialContext tvContext = new TvSerialContext();
List<TVSerial> tv = tvContext.TvSerials.Where(tvs => tvs.Series_Name == serial).Distinct().ToList();
return View(tv);
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
它返回所有行,我只想从每个series_name和自定义字段"Series_Name,Season_No,Image_Url_Big"中选择一行 我不知道如何实现这一目标. 得到结果:
it return all rows , i just want single row from every series_name and custom field "Series_Name,Season_No,Image_Url_Big" i don't know how to achieve this. getting result :
预期结果:-
推荐答案
您可以通过创建视图模型并使用.GroupBy()
子句
You could do this by creating a view model and using a .GroupBy()
clause
public class TVSerialVM
{
public string SeriesName { get; set; }
public string SeasonNo { get; set; }
public string ImageUrl { get; set; }
}
以及要投影到您的视图模型中的查询
and the query to project into your view model
List<TVSerialVM> model = tvContext.TvSerials.Where(t => t.Series_Name == serial)
.GroupBy(t => new { t.Series_Name, t.Season_No, t.Image_Url_Big })
.Select(t => new TVSerialVM
{
SeriesName = t.Key.Series_Name,
SeasonNo = t.Key.Season_No,
ImageUrl = t.Key.Image_Url_Big
}).ToList();
旁注:您在数据库中的重复数据(季节编号和图像url).您应该考虑将图片网址移到与季节编号相关的另一张表中.
Side note: Your duplicating data in the database (the season number and the image url). You should consider moving the image urls to another table with a relationship to the season number.
这篇关于如何在MVC中绑定自定义模型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!