Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在ASP.NET页面中从数据库检索数据_C#_Sql_Asp.net_Entity Framework_Razor - Fatal编程技术网

C# 在ASP.NET页面中从数据库检索数据

C# 在ASP.NET页面中从数据库检索数据,c#,sql,asp.net,entity-framework,razor,C#,Sql,Asp.net,Entity Framework,Razor,我在网上找到了如何将用户上传的图像提交到我的数据库中。以下是我使用的代码: Create.cshtml @page @model SummerFling.Pages.Products.CreateModel @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <

我在网上找到了如何将用户上传的图像提交到我的数据库中。以下是我使用的代码:

Create.cshtml

@page
@model SummerFling.Pages.Products.CreateModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>

<h4>Product</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form enctype="multipart/form-data" method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Product.ProductName" class="control-label"></label>
                <input asp-for="Product.ProductName" class="form-control" required />
                <span asp-validation-for="Product.ProductName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Product.ProductShortDesc" class="control-label"></label>
                <input asp-for="Product.ProductShortDesc" class="form-control" required />
                <span asp-validation-for="Product.ProductShortDesc" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Product.ProductLongDesc" class="control-label"></label>
                <input asp-for="Product.ProductLongDesc" class="form-control" required />
                <span asp-validation-for="Product.ProductLongDesc" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Product.ProductPrice" class="control-label"></label>
                <input asp-for="Product.ProductPrice" class="form-control" required />
                <span asp-validation-for="Product.ProductPrice" class="text-danger"></span>
            </div>
            <dl>
                <dt>
                    <label asp-for="FileUpload.FormFile"></label>
                </dt>
                <dd>
                    <input asp-for="FileUpload.FormFile" type="file" required>
                </dd>
            </dl>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
</body>
</html>
@page
@model SummerFling.Pages.Products.IndexModel
@using WebMatrix.Data;

@{
    Layout = null;
    var queryString = "SELECT ProductImage1 FROM Image WHERE ProductID LIKE @0";
    var db = Database.Open("SummerFlingProductContext");

    // appsettings.json
    //   "ConnectionStrings": {
    //       "SummerFlingProductContext": "Server=127.0.0.1,1433;Database=SummerFling;User Id=SA;Password=******;MultipleActiveResultSets=true"
    //    }

}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
        <a asp-page="Create">Create New</a>
    </p>
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Product[0].ProductName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Product[0].ProductShortDesc)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Product[0].ProductLongDesc)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Product[0].ProductPrice)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Product)
            {

                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductShortDesc)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductLongDesc)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductPrice)
                    </td>
                    <td>
                        @db.QuerySingle(queryString, item.ProductID);
                    </td>
                    <td>
                        <a asp-page="./Edit" asp-route-id="@item.ProductID">Edit</a> |
                        <a asp-page="./Details" asp-route-id="@item.ProductID">Details</a> |
                        <a asp-page="./Delete" asp-route-id="@item.ProductID">Delete</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</body>
</html>
@page
@模型SummerFling.Pages.Products.CreateModel
@{
布局=空;
}
创造
产品

返回列表 @节脚本{ @{wait Html.RenderPartialAsync(“_validationScript”);} }
在Create.cshtml.cs类文件中,我有从表单中获取数据并将其提交到数据库的代码:

Create.cshtml.cs

// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    using (var memoryStream = new MemoryStream())
    {
        await FileUpload.FormFile.CopyToAsync(memoryStream);

        // Upload the file if less than 2 MB
        if (memoryStream.Length < 2097152)
        {
            var imageRecord = new Image()
            {
                ProductImage1 = memoryStream.ToArray()
            };

            _context.Image.Add(imageRecord); // Add the created image record to the Image database.

            await _context.SaveChangesAsync();

            _context.Product.Add(Product); // Add the created product record to the Product database

            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }
        else
        {
            ModelState.AddModelError("File", "The file is too large.");
            return Page();
        }
    }

}
namespace SummerFling.Pages.Products
{
    public class IndexModel : PageModel
    {
        private readonly SummerFling.Data.SummerFlingProductContext _context;

        public IndexModel(SummerFling.Data.SummerFlingProductContext context)
        {
            _context = context;
        }

        public IList<Product> Product { get; set; }
        public IList<Image> Image { get; set; }

        public async Task OnGetAsync()
        {
            Product = await _context.Product.ToListAsync();
            IList<Image> Image = await _context.Image.ToListAsync();
        }
    }
}
//若要防止套印攻击,请启用要绑定到的特定属性,例如
//更多详细信息请参见https://aka.ms/RazorPagesCRUD.
公共异步任务OnPostAsync()
{
如果(!ModelState.IsValid)
{
返回页();
}
使用(var memoryStream=new memoryStream())
{
等待FileUpload.FormFile.CopyToAsync(memoryStream);
//如果小于2 MB,请上载文件
如果(内存流长度<2097152)
{
var imageRecord=新图像()
{
ProductImage1=memoryStream.ToArray()
};
_context.Image.Add(imageRecord);//将创建的图像记录添加到图像数据库中。
wait_context.SaveChangesAsync();
_context.Product.Add(Product);//将创建的产品记录添加到产品数据库中
wait_context.SaveChangesAsync();
返回页首(“/索引”);
}
其他的
{
AddModelError(“文件”,“文件太大”);
返回页();
}
}
}
现在,在/Index页面上,我想获取存储在数据库中的所有数据,并在页面上显示这些数据。我对存储在产品表中的数据这样做没有问题,但是我很难理解我应该如何对存储在图像表中的图像这样做的逻辑

Index.cshtml

@page
@model SummerFling.Pages.Products.CreateModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>

<h4>Product</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form enctype="multipart/form-data" method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Product.ProductName" class="control-label"></label>
                <input asp-for="Product.ProductName" class="form-control" required />
                <span asp-validation-for="Product.ProductName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Product.ProductShortDesc" class="control-label"></label>
                <input asp-for="Product.ProductShortDesc" class="form-control" required />
                <span asp-validation-for="Product.ProductShortDesc" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Product.ProductLongDesc" class="control-label"></label>
                <input asp-for="Product.ProductLongDesc" class="form-control" required />
                <span asp-validation-for="Product.ProductLongDesc" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Product.ProductPrice" class="control-label"></label>
                <input asp-for="Product.ProductPrice" class="form-control" required />
                <span asp-validation-for="Product.ProductPrice" class="text-danger"></span>
            </div>
            <dl>
                <dt>
                    <label asp-for="FileUpload.FormFile"></label>
                </dt>
                <dd>
                    <input asp-for="FileUpload.FormFile" type="file" required>
                </dd>
            </dl>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
</body>
</html>
@page
@model SummerFling.Pages.Products.IndexModel
@using WebMatrix.Data;

@{
    Layout = null;
    var queryString = "SELECT ProductImage1 FROM Image WHERE ProductID LIKE @0";
    var db = Database.Open("SummerFlingProductContext");

    // appsettings.json
    //   "ConnectionStrings": {
    //       "SummerFlingProductContext": "Server=127.0.0.1,1433;Database=SummerFling;User Id=SA;Password=******;MultipleActiveResultSets=true"
    //    }

}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
        <a asp-page="Create">Create New</a>
    </p>
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Product[0].ProductName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Product[0].ProductShortDesc)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Product[0].ProductLongDesc)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Product[0].ProductPrice)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Product)
            {

                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductShortDesc)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductLongDesc)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ProductPrice)
                    </td>
                    <td>
                        @db.QuerySingle(queryString, item.ProductID);
                    </td>
                    <td>
                        <a asp-page="./Edit" asp-route-id="@item.ProductID">Edit</a> |
                        <a asp-page="./Details" asp-route-id="@item.ProductID">Details</a> |
                        <a asp-page="./Delete" asp-route-id="@item.ProductID">Delete</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</body>
</html>
@page
@模型SummerFling.Pages.Products.IndexModel
@使用WebMatrix.Data;
@{
布局=空;
var queryString=“从ProductID类似于@0的图像中选择ProductImage1”;
var db=Database.Open(“SummerFlingProductContext”);
//appsettings.json
//“连接字符串”:{
//“SummerFlingProductContext”:“服务器=127.0.0.11433;数据库=SummerFling;用户Id=SA;密码=*****;MultipleActiveResultSets=true”
//    }
}
指数

创造新的

@Html.DisplayNameFor(模型=>model.Product[0].ProductName) @Html.DisplayNameFor(model=>model.Product[0].ProductShortDesc) @Html.DisplayNameFor(model=>model.Product[0].ProductLongDesc) @Html.DisplayNameFor(model=>model.Product[0].ProductPrice) @foreach(Model.Product中的var项) { @Html.DisplayFor(modelItem=>item.ProductName) @DisplayFor(modelItem=>item.ProductShortDesc) @DisplayFor(modelItem=>item.ProductLongDesc) @DisplayFor(modelItem=>item.ProductPrice) @db.QuerySingle(queryString,item.ProductID); 编辑| 细节| 删除 }
Index.cshtml.cs

// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    using (var memoryStream = new MemoryStream())
    {
        await FileUpload.FormFile.CopyToAsync(memoryStream);

        // Upload the file if less than 2 MB
        if (memoryStream.Length < 2097152)
        {
            var imageRecord = new Image()
            {
                ProductImage1 = memoryStream.ToArray()
            };

            _context.Image.Add(imageRecord); // Add the created image record to the Image database.

            await _context.SaveChangesAsync();

            _context.Product.Add(Product); // Add the created product record to the Product database

            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }
        else
        {
            ModelState.AddModelError("File", "The file is too large.");
            return Page();
        }
    }

}
namespace SummerFling.Pages.Products
{
    public class IndexModel : PageModel
    {
        private readonly SummerFling.Data.SummerFlingProductContext _context;

        public IndexModel(SummerFling.Data.SummerFlingProductContext context)
        {
            _context = context;
        }

        public IList<Product> Product { get; set; }
        public IList<Image> Image { get; set; }

        public async Task OnGetAsync()
        {
            Product = await _context.Product.ToListAsync();
            IList<Image> Image = await _context.Image.ToListAsync();
        }
    }
}
namespace SummerFling.Pages.Products
{
公共类索引模型:PageModel
{
私有只读SummerFling.Data.SummerFlingProductContext\u context;
公共索引模型(SummerFling.Data.SummerFlingProductContext)
{
_上下文=上下文;
}
公共IList乘积{get;set;}
公共IList映像{get;set;}
公共异步任务OnGetAsync()
{
Product=wait_context.Product.toListSync();
IList Image=wait_context.Image.tolistSync();
}
}
}
我正在努力找出应该在哪里以及如何编写逻辑代码,以便从图像表中获取图像,并将图像与每行的所有其他数据一起显示。(现在,图像表中的条目1包含与产品表中的条目1相关的图像)


我是否在.cshtml.cs文件中以类似于从产品表中检索数据的方式对其进行编码?我该怎么做呢?

您需要在显示
Index.cshtml
视图的控制器中检索图像。 此外,还可以将图像添加到
IndexModel
的(列表)中,并以与显示
ProductName
ProductShortDes
相同的方式显示图像


通常,您希望视图中的逻辑尽可能少,尤其是数据库ac。

图像列表应该是什么类型?在存储到列表中之前,是否将字节流转换为对象?例如,什么