如何从剃须刀页面访问列表属性

时间:2018-12-14 19:07:49

标签: c# entity-framework model-view-controller razor-pages

在查看页面(cshtml)中,我想访问实体,例如产品详细信息,价格或我所用的东西。首先,对于产品模型,它包含以下属性:

        public int ProductId { get; set; }
        public int? CatId { get; set; }
        public string ProductSdesc { get; set; }
        public string ProductLdesc { get; set; }
        public string ProductImage { get; set; }
        public decimal? Price { get; set; }
        public bool? Instock { get; set; }
        public int Inventory { get; set; }

        public ProductCategories Cat { get; set; }

所以我想在视图页面(cshtml)中访问这些属性之一

以下是我的代码试图在C#剃须刀页面中获取该属性。

public class ElectronicDetailsModel : PageModel
    {
        private readonly XYZshopping.Models.XYZEVEDBContext _context;
        private readonly IHttpContextAccessor _httpContextAccessor;

        [BindProperty]
        public IList<Products> Products { get; set; }

        public ElectronicDetailsModel(XYZshopping.Models.XYZEVEDBContext context, IHttpContextAccessor httpContextAccessor)
        {
            _context = context;
            _httpContextAccessor = httpContextAccessor;
        }

        public IActionResult OnGet()
        {
            //var userName = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name).Value;

            Products = _context.Products.Where(p => p.CatId == 10).ToList();

            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            Products = _context.Products.Where(p => p.CatId == 10).ToList();

            await _context.SaveChangesAsync();

            return RedirectToPage("./TransferSToC");
        }
    }

获取价格或ProductSdesc ..在视图页面中应该是什么样的?

<div class="row">
    <div class="col-md-4">
        <form>
            @Model.Products.... < this part I am trying to implement...> How can I access the property in the C# (controller page) ??
        </form>
</div>

-编辑- 要了解我要做什么, 在浏览器上,我希望这些可视化如下: Casio HandHeld Color1 TV 2.7 --> ProductSDec $45.0000 --> Price

1 个答案:

答案 0 :(得分:2)

<form method="post">
    @foreach (var product in Model.Products)
    {
        <tr>
            <td>@product.Price</td>
            <td>@product.etc...</td>
        </tr>
    }
</form>

<form method="post">
    @for (int i = 0; i < Model.Products.Count; i++)
    {
        <tr>
            <td>@Html.DisplayFor(p => p.Products[i].Price)</td>
        </tr>
    }
</form>