繁体   English   中英

如何在视图中从多个表显示

[英]How to Display From Multiple Tables From Within View

我试图在索引视图中显示ApplicationUser表和Listings表中的数据。

这是我的ApplicationUser

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
    [InverseProperty("Seller")]
    public virtual ICollection<Listing> SellerListings { get; set; }
    [InverseProperty("Buyer")]
    public virtual ICollection<Listing> BuyerListings { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string Address { get; set; }
}

这是我的列表Pocos

public class Listing
{
    public int ListingId { get; set; }

    [ForeignKey("Seller")]
    public string SellerId { get; set; }
    public virtual ApplicationUser Seller { get; set; }

    [Required]
    public string ItemCategory { get; set; }

    [Required]
    public string ItemName { get; set; }

    [Required]
    public decimal Cost { get; set; }

    public DateTime DateOfPublish { get; set; }

    [Required]
    public bool SaleStatus { get; set; }

    [ForeignKey("Buyer")]
    public string BuyerId { get; set; }
    public virtual ApplicationUser Buyer { get; set; }
}

在我的索引视图中

@model IEnumerable<Pocos.Listing>

我想显示我要使用的卖方(用户)的用户名

@Html.DisplayNameFor(model => model.Seller.UserName)

但这即使卖方已正确填充也将显示为空白

编辑:可能是我的控制器和存储库出了问题这是我的控制器:

public ActionResult Index()
    {
        List<Listing> listing = client.GetAllListings();
        return View(listing);

这是我的存储库中的方法:

public List<Listing> GetAllListings()
    {
        return context.Listing.ToList();
    }

只需使用@直接呈现值:

<p>
    <span>User name:</span>
    @this.Model.Seller.UserName
</p>

如果需要执行进一步的视图级处理,则可以使用括号:

<p>
    <span>User name:</span>
    @( this.Model.Seller.UserName + " some concatenated string" )
</p>

如果确实将[DisplayName]属性添加到UserName属性,则仍可以使用DisplayNameFor ,如下所示:

ApplicationUser.cs:

[DisplayName("User name")]
public String UserName { get; set; }

View.cshtml:

<p>
    <span>@Html.DisplayNameFor( m => m.Seller.UserName )</span>
    @( this.Model.Seller.UserName + " some concatenated string" )
</p>

如果您愿意的话,这将有助于将来的本地化,因为视图中未嵌入英语文本“用户名”。 您将需要使用DisplayNameAttribute的子类,该子类接受资源名称而不是const字符串。

请注意,如果您的控制器具有接受IdentityUser对象的POST操作,则您的应用程序将容易受到模型覆盖攻击。 因此,我不建议将实体类型用于ViewModel数据,对于敏感数据,您应该具有专用的单向ViewModel。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM