Can we display linq result in view without model
Rahul M...
4960
Points
31
Posts
|
Hi Avnish, You can use ViewBag or ViewData but not recommended. Also as we know you can pass only on model to a view. There are two way you can do desire as you say.
If you are doing something, post some code snippet so that we can help you more accurately.
Posted On:
05-Jun-2016 20:03
|
NiceOne...
1390
Points
18
Posts
|
Follow the following example by using ViewBag In controller var User = (from u in DbContext.User select u);
ViewBag.User = User;
In View @foreach (var item in ViewBag.User) {
@item.UserName
}
Posted On:
06-Jun-2016 00:15
|
avnish
242
Points
11
Posts
|
yes but i was not able to use it when I used inner join in query IN CONTROLLER var q = (from ED in cc.EmpDetails
join DT in cc.Department
on ED.DepartmentID equals DT.DepartmentID
select new { ED.Name, DT.DepartmentName }); ViewBag.ListData = q;
IN View foreach (var item in ViewBag.ListData) { @item.Name @item.DepartmentName }
Posted On:
06-Jun-2016 00:29
|
NiceOne...
1390
Points
18
Posts
|
Ok, Since you are using anonymous object select new{..} to return. You should create a model class as public class EmpTemp {
public string Name { get; set; }
public string DepartmentName { get; set; }
}
And then your controller as var q = (from ED in cc.EmpDetails
join DT in cc.Department
on ED.DepartmentID equals DT.DepartmentID
select new EmpTemp{
Name=ED.Name,
DepartmentName= DT.DepartmentName
});
and in view you can access as @foreach (EmpTemp item in ViewBag.ListData) {
@item.Name
@item.DepartmentName
}
Posted On:
06-Jun-2016 00:53
|
avnish
242
Points
11
Posts
|
Well we can do it with Expando Object In Model public static class Expando {
public static ExpandoObject ToExpando(this object anonymousObject) {
IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}
}
IN Controller dynamic Query = (from ED in cc.EmpDetails
join DT in cc.Department on ED.DepartmentID equals DT.DepartmentID
orderby ED.EmpID
select new {
ED.EmpID,
ED.Name,
DT.DepartmentName,
}).ToList().Select(c => c.ToExpando());
ViewBag.ListData = Query;
IN VIEW @foreach(dynamic item in ViewBag.ListData) {
@item.Name
@item.DepartmentName
}
Posted On:
07-Jun-2016 12:01
|
NiceOne...
1390
Points
18
Posts
|
Hi avnish, Great! ToExpando is a extension method on the Object Type. Extension methods are available from the 3.5 version of the .NET Framework. Extension methods enable us to "add" methods to existing types (like int, String, etc) without creating a new derived type, recompiling, or otherwise modifying the original type. See more about Extension method at https://www.niceonecode.com/Blog/DotNet/CSharp/Extension-Methods-in-csharp/7
Posted On:
07-Jun-2016 18:32
|