【发布时间】:2019-04-11 10:10:36
【问题描述】:
我在控制器中有一个 index 方法,如下所示:
public ActionResult Index()
{
var object = _ObjectService.GetAll();
return View(object);
}
这给了我一个具有这些属性的对象列表:
public class Object : EntityWithNameAndId
{
public virtual Site Site { get; set; }
public virtual List<User> Users { get; set; }
public virtual List<Planning> Plannings { get; set; }
public virtual Guid IdPilote { get; set; }
}
现在在我的 Index() 视图中,我想获取与 IdPilote id 相关的用户并显示其名称。
我试过这样的东西,感谢这个话题ASP.Net MVC: Calling a method from a view:
@model List<MyClass.Models.Promotion>
@foreach (var item in Model)
{
<td>@item.Site.Name</td>
@{
var id = item.IdPilote;
//Here Interface and Service are folders
var user = MyDAL.Interface.Service.IUserService.Get(id);
}
<td>
//This is where i try to display my User name,
//that i get dynamically using the idPilote for each User in list
</td>
}
但 Get(id) 未被识别为有效方法..
public interface IUserService : IDisposable
{
User Get(Guid id);
}
public class UserService : IUserService
{
private MyContext context;
public UserService(MyContext context)
{
this.context = context;
}
public User Get(Guid id)
{
return context.User.Where(w => w.Id == id).SingleOrDefault();
}
}
那么什么是让我的用户对象进入我的视图的最佳方法,因为我只得到一个 Id ?
我应该在我的 Index 方法(我可以调用 IUserInterface.Get())中使用第一个列表创建一个新列表,还是有更好的方法?
【问题讨论】:
-
在一个普通的 MVC 应用程序中,你在 Controller 和 View 之间传递一个叫做 ViewModel 的东西。您不应该在视图中调用 Repository/Service。
-
我确实有 ViewModel,但我的索引视图 @model 是一个 List
。我会编辑我的帖子 -
为视图创建单独的视图模型,以便更好地在视图中不直接使用 db 实体,因为您可能使用不同的验证或使用
data-annotations,因此将您的对象绑定到视图模型并传递给视图
标签: c# asp.net-mvc