我是MVC5的新手,我遇到了麻烦。 有人可以帮助我吗?
我有2个表,DocMain(Doc_Id,Doc_Title)
,DocProduct(Doc_Id,Doc_Content)
,
我想通过相同的Doc_Id
选择2个表格内容。
然后循环它们。
显示如下:
<ul>
<li><a href="1">title1</a>content1</li>
<li><a href="2">title2</a>content2</li>
<li><a href="3">title3</a>content3</li>
</ul>
.... 怎么做?
//Here is my viewmodel
public class MainProductViewModel
{
public IEnumerable<DocMainListView> DocMainListView { get; set; }
public IEnumerable<DocProductListView> DocProductListView { get; set; }
}
-------------------------------------------------
//Here is my controller
public class DocProductController : Controller
{
private IDocProductRepository repository;
private IDocMainRepository repositoryMain;
public DocProductController(IDocProductRepository docProductRepository, IDocMainRepository docMainRepository)
{
this.repository = docProductRepository;
this.repositoryMain = docMainRepository;
}
public ActionResult List()
{
var products = from docProduct in repository.DocProduct
join docMain in repositoryMain.DocMain
on docProduct.Doc_Id equals docMain.Doc_Id
select new { DocMainTitle = docMain.Doc_Title, DocProductContent = docProduct.DocProduct_Content };
//ViewBag.products = products;
//DocProductListView model = new DocProductListView
//{
// DocProduct = repository.DocProduct
// .Join(repositoryMain.DocMain,
// docProduct => docProduct.Doc_Id,
// docMain => docMain.Doc_Id,
// (docProduct, docMain) => new { a = docMain.Doc_Id, b = docProduct.Doc_Id })
// .OrderByDescending(n => n.)
//};
return View(products);
}
}
我不知道如何编写控制器代码和查看代码。
答案 0 :(得分:0)
由于您只想显示标题和内容,因此您的视图模型将是
public class MainProductViewModel
{
public IEnumerable<ProductInfo> Products { get; set;}
}
public class ProductInfo
{
public string DocMainTitle { get; set;}
public string DocProductContent { get; set;}
}
您的查询将是:
var products = from docProduct in repository.DocProduct
join docMain in repositoryMain.DocMain
on docProduct.Doc_Id equals docMain.Doc_Id
select new ProductInfo { DocMainTitle = docMain.Doc_Title, DocProductContent =
docProduct.DocProduct_Content };
将此产品分配给MainProductViewModel的产品并返回查看,然后将您的视图配置为
@model MainProductViewModel