【问题标题】:How to retrieve an object property inside a view如何在视图中检索对象属性
【发布时间】: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


【解决方案1】:

按照建议,通过创建一个新列表和一个特定的 ViewModel 使其工作:

public class IndexObjectViewModel : EntityWithNameAndId
{
    public virtual Site Site { get; set; }
    public virtual List<User> Users { get; set; }
    public virtual List<Planning> Plannings { get; set; }

    //To store User instead of its Id
    public virtual User Pilote { get; set; }
}

现在 Index() 看起来像这样:

public ActionResult Index()
{
    var objects = _IObjectService.GetAll();
    ViewBag.NotPromoExist = false;

    var indexObj = new List<IndexObjectViewModel>();           

    foreach (var p in objects)
    {
        var indexModel = new IndexObjectViewModel();

        indexModel.Id = p.Id;
        indexModel.Name = p.Name;
        indexModel.Site = p.Site;
        indexModel.Users = p.Users;
        indexModel.Plannings = p.Plannings;
        indexModel.Pilote = _IUserService.Get(p.IdPilote);

        indexObj.Add(indexModel);
    }

    return View(indexObj);
}

现在一切都在控制器中完成了。不确定这是否是最好的方法..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2017-05-18
    相关资源
    最近更新 更多