首页 > 解决方案 > 如何在 MVC asp.net core 中上传文件 + 在 sql server 上更新?

问题描述

我想在 MVC dot net core 2 中上传文件,我是学生并且是这项技术的新手(我在这里阅读了一些问答,但没有回答这个问题)。

我的产品模型有一个添加操作和视图。在视图中,有一个表单可以创建具有某些属性的产品。我还想添加一个上传图片的选项 - 单击添加按钮后,需要先使用实体​​框架代码将产品保存在数据库中。

我不使用 ViewModel(并且我不想要它的解决方案),但也许稍后我会想为 Image 实体创建类。不是现在(对我来说太多了)。

请帮我怎么做。这是代码。

型号 - 产品:

public class Product
    {
        [Key]
        public Guid Id { get; set; }
        [Required]
        [StringLength(50, MinimumLength = 3)]
        public string Name { get; set; }
        [Required]
        public string Description { get; set; }
        [Required]
        public string Category { get; set; }
        [Required]
        public string Gender { get; set; }
        [Required]
        public string Age { get; set; }
        [Required]
        public bool ConditionIsNew { get; set; }
    }

控制器 - 产品控制器

public class ProductController : Controller
    {
            [HttpGet]
            public IActionResult Add()
            {
                return View(new Product());
            }

            [HttpPost]
            public IActionResult Add(Product p)
            {
                if (ModelState.IsValid)
                {
                    ProductDal dal = new ProductDal();
                    dal.Products.Add(p);
                    dal.SaveChanges();
                    return View("Show", p);
                }
                return View(p);
            }
    }

查看 - 添加(Razor 语法、标签助手)

@model MyProjectTest.Models.Product
    @{
        Layout = "~/Shared/_Layout.cshtml";
    }
<h1>Submit</h1>
    <h2>Add product</h2>
    <form asp-controller="Product" asp-action="Add" method="post">
            <label asp-for="Name"></label> <input asp-for="Name" /> <span asp-validation-for="Name"></span>
            <br />
            <label asp-for="Description"></label> <input asp-for="Description" /> <span asp-validation-for="Description"></span>
            <br />
            <label asp-for="Category"></label> <input asp-for="Category" /> <span asp-validation-for="Category"></span>
            <br />
            <label asp-for="Gender"></label> <input asp-for="Gender" /> <span asp-validation-for="Gender"></span>
            <br />
            <label asp-for="Age"></label> <input asp-for="Age" /> <span asp-validation-for="Age"></span>
            <br />
            <label asp-for="ConditionIsNew"></label> <input asp-for="ConditionIsNew" /> <span asp-validation-for="ConditionIsNew"></span>
            <br />
            <input id="SubmitProduct" type="submit" value="Enter" />
        </form>

同样,我没有 ViewModel,也不想使用它。

我也想知道如何将图像更新到数据库

谢谢

标签: c#asp.net-mvcmodel-view-controller

解决方案


Html 层:* input type="file" name="fileABC"/>

控制器层:方法 html post,参数为 HttpPostedFileBase 类型并命名为 fileABC(在这种情况下,必须与模型的参数分开为产品模型)

对于 SQL:使用 blob、文件流 ...


推荐阅读