我如何在asp.net Core中创建主详细信息页面

时间:2020-02-11 03:42:12

标签: c# asp.net-mvc asp.net-core

如何在asp.net核心MVC中的视图中显示数据?

我有以下json格式数据

[
    {
      "ProductID": "100000",
      "ProductName": "Product 1"
    },
    {
      "ProductID": "100001",
      "ProductName": "Product 2"
    },
    {
      "ProductID": "100002",
      "ProductName": "Product 3"
    },
    {
      "ProductID": "100002",
      "ProductName": "Product 4"
    }
]

我有这段代码来读取上述json数据,以便从上述json数据中读取产品信息

public class GetProducts_Action : BaseEFAction<GetProducts_Action_Request, GetProducts_Action_Response>
    {
        public IFileProvider FileProvider { get; }

        public GetProducts_Action(ILogger<GetProducts_Action> logger, DBContext context, ITransactionManager scope, IFileProvider fileProvider) : base(logger, context, scope)
        {
            FileProvider = fileProvider;
        }

        protected override Task<GetProducts_Action_Response> PerformActionAsync(GetProducts_Action_Request request)
        {
            IList<ProductDTO> product;

            using (var file = System.IO.File.OpenText(FileProvider.GetFileInfo("Product.json").PhysicalPath))
            {
                var serializer = new JsonSerializer();
                product = (IList<ProductDTO>)serializer.Deserialize(file, typeof(IList<ProductDTO>));
            }

            return Task.FromResult(new GetProducts_Action_Response { Products = product });
        }
    }

    public class GetProducts_Action_Request : BaseActionRequest
    {

    }

    public class GetProducts_Action_Response : BaseActionResponse
    {
        public IList<ProductDTO> Products { get; set; }
    }
}

接口:

public interface IProductService { Task<IList<ProductDTO>> GetProduct(); }

显示所有效果很好的产品的控制器动作

public IActionResult Index()
{
    return View();
}

[HttpGet]
public async Task<IActionResult> GetProducts()
{
    var products = await ProductsService.GetProducts();
    return Json(products);
}

我能够使用上面的代码显示所有产品,并且效果完美,我还创建了指向详细信息页面的链接,URL看起来像这样localhost:3000/Product/Products/102。但是如何通过ID获取产品信息并显示在详细信息页面?。

我尝试过

   [HttpGet("{id}")]
public async Task<IActionResult> GetProductsDetail(int id)
{
    var product = (await ProductsService.GetProducts()).FirstOrDefault(a => a.ProductCode == id);
    if (product != null) {
        return Json(product);
    } else {
        return NotFound();
    }
}

但是我得到

无法将类型'System.Collections.Generic.List隐式转换为 'System.Collections.IList'

ProductList结构

 public class ProductList
    {
       public string ProductCode { get; set; }
       public string ProductName { get; set; }
    }

详细视图中的网格为

 @model ProductList

                                <div class="row">
                                @(Html.Kendo().Grid<ProductList>()
                               .Name("grid")
                                .Columns(cols =>
                                {
                                      cols.Bound(ProductList => ProductList.ProductCode).Hidden(false).Title(Localizer["Column 1"].Value);
                                      cols.Bound(ProductList => ProductList.ProductName).Hidden(false).Title(Localizer["Column 2"].Value);
                                 })
                                //.Editable(e => e.Mode(GridEditMode.PopUp).TemplateName(""))
                                .Excel(excel => excel
                                .FileName("Kendo UI Grid Export.xlsx")
                                .Filterable(true)
                                .ProxyURL(Url.Action("Excel_Export_Save", "Grid"))
                                )
                                .Navigatable(true)
                                .Filterable(f => f.Enabled(true).Mode(GridFilterMode.Row))
                                .Scrollable(s => s.Enabled(true))
                                .Sortable()
                                .PersistSelection()
                                .Pageable(pageable => pageable
                                .ButtonCount(5)
                                .Refresh(true)
                                .PageSizes(new[] { 5, 10, 20 }))
                                .DataSource(dataSource => dataSource
                                             .Custom()
                                             .PageSize(10)
                                             .Transport(transport => transport
                                             .Read(read => read.Action("GetProductsDetail", "Product"))

                                             ))
                                )

                            </div>

1 个答案:

答案 0 :(得分:2)

首先,您可以从此获得结果

var listOfproducts = (await ProductsService.GetProducts().ToList());

之后,您可以获得价值

var product = listOfproducts.FirstOrDefault(a => a.ProductCode == id);

其次,如我所见,GetProductsDetail返回了Json,因此您正在使用Ajax。如果您想重定向到页面:

  1. 在索引视图中:
@Html.ActionLink("You_Controller_Name", "GetProductsDetail", new { id = item.ID }) |
  1. 您应该返回return View(product);而不是Json

阅读以下文章以更好地了解

Get Started with Entity Framework 6 Code First using MVC 5

Passing Data from the Controller to the View