Good time of a day!
I have a MVC project with query in controller:
var getPhotos = (from m in db.photos
join n in db.comments on m.id equals n.photoid
where n.ownerName == User.Identity.Name
orderby n.id descending
select new {
m.imgcrop, m.id,
n.commenterName, n.comment
}).Take(10);
How to pass this query to view model, and the model to view.
Spend all evening to find the examples, but cant. Thanks for help!
UPDATED
Full Model Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace photostorage.Models
{
public class GlobalModel
{
public class PhotoViewModel
{
public photos Photos { get; set; }
public profiles Profile { get; set; }
public IQueryable<comments> Comments { get; set; }
public IQueryable<photos> NextPrev { get; set; }
}
public class UserPhotoList
{
public IQueryable<photos> Photos { get; set; }
public profiles Profile { get; set; }
}
public class UserProfileView
{
public IQueryable<photos> Photos { get; set; }
public profiles Profile { get; set; }
}
public class GetLastComments
{
public IQueryable<photos> uPhoto { get; set; }
public IQueryable<comments> uComments { get; set; }
}
}
}
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using photostorage.Models;
namespace photostorage.Controllers
{
public class HomeController : Controller
{
private photostorageEntities db = new photostorageEntities();
public ActionResult Index()
{
if(Request.IsAuthenticated) {
GlobalModel.GetLastComments model = new GlobalModel.GetLastComments();
var getPhotos = (from m in db.photos
join n in db.comments on m.id equals n.photoid
where n.ownerName == User.Identity.Name
select new {
m.imgcrop, m.id,
n.commenterName, n.comment
}).Take(10);
return View("Index_Auth", model);
}else{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View("Index");
}
}
public ActionResult About()
{
return View();
}
}
}
In this case you can make a “view model” that will only be used by your view and not by the rest of your application. Something like the following:
Then change your query like so:
Make your view strongly typed to the new class and pass the data to it like so: