C# 如何使用LINQ将值传递给ViewModel?
我需要使用LINQ向视图模型添加数据 我的视图模型是:C# 如何使用LINQ将值传递给ViewModel?,c#,asp.net-mvc,linq,mvvm,model,C#,Asp.net Mvc,Linq,Mvvm,Model,我需要使用LINQ向视图模型添加数据 我的视图模型是: public class SearchScrapViewModel { public WClass wClass{get; set;} public SClass sClass{get; set;} public YClass yClass { get; set; } } public class WClass { public string title { get; set; } public string link
public class SearchScrapViewModel
{
public WClass wClass{get; set;}
public SClass sClass{get; set;}
public YClass yClass { get; set; }
}
public class WClass
{
public string title { get; set; }
public string link { get; set; }
}
public class SClass
{
public string title { get; set; }
public string link { get; set; }
}
public class YClass
{
public string title { get; set; }
public string link { get; set; }
}
我需要将这3个类与3个不同的LINQ查询一起使用,然后将数据传递给返回视图(SearchScrapViewModel)代码>
与其他课程类似
然后传递到返回视图(SearchScrapViewModel)代码>以便我可以访问此控制器视图中的所有3个类
如何做到这一点?LINQ并不是最终的解决方案,我不知道这是否是您所寻找的最佳解决方案。我建议看一下,来完成这个。如果您真的想这样做,您可以在一个LINQ查询中(使用对象初始值设定项)完成这项工作,但它可能不像构建器那样清晰(但这是我的两分钱):
您忘记创建WClass的实例:
select new SearchScrapViewModel {
wClass = new WClass {
link = link.Attributes["href"].Value,
title = link.InnerText
}
};
或者,您可以使WClass(以及SClass和YClass)成为一个类而不是一个类,这样您就不需要实例化它。但是,在这种情况下,您可能应该这样做。我不清楚为什么在示例中需要select语句。在任何情况下,都不能将SearchScrapViewModel作为返回返回,因为它是一个类型而不是实例。除非您的代码为本文简化,并且您确实需要linq,否则我建议:
var wikians =
new SearchScrapViewModel {
wClass = new WClass {
link = link.Attributes["href"].Value,
title = link.InnerText
}
};
return View(wikians);
好的…我用过这个…但是现在如何通过。。。这是要查看的。。。我的意思是使用“返回视图(SearchScrapViewModel)”不起作用…我是否需要在viewmodel中做一些更改,以便我可以使用此主SearchScrapViewModel将所有类数据传递给视图?我使用了@Heinzi建议的方法。但如何将此传递给视图。。。我的意思是使用“返回视图(SearchScrapViewModel)”不起作用…我是否需要在viewmodel中做一些更改,以便我可以使用此主SearchScrapViewModel将所有类数据传递给视图?
select new SearchScrapViewModel {
wClass = new WClass {
link = link.Attributes["href"].Value,
title = link.InnerText
}
};
var wikians =
new SearchScrapViewModel {
wClass = new WClass {
link = link.Attributes["href"].Value,
title = link.InnerText
}
};
return View(wikians);