针对特定商店的类别模型的多项选择ASP.Net MVC

如何解决针对特定商店的类别模型的多项选择ASP.Net MVC

我想针对选定的商店标记多个类别。目前,使用我的功能,每个商店只能分配1个类别。但是,我希望以一种可以为任何商店分配多个类别的方式编写代码。 示例:Amazon Store应该具有多个类别,例如时尚,智能手机,电子产品等等。我目前的代码只分配给了智能手机。

  1. 商店模型类
public class Store
    {

        [Key]
        public int StoreID { get; set; }
        [Required]
        public string StoreName { get; set; }
        public string StoreLogo { get; set; }
        [AllowHtml]
        public string TopDesc { get; set; }
        [AllowHtml]
        public string MainDesc { get; set; }
        public int CatID { get; set; }
        public string CatName { get; set; }
        public string Slug { get; set; }        
        public string MetaDesc { get; set; }

        [ForeignKey("CatID")]
        public virtual Category Category { get; set; }

        public IEnumerable<SelectListItem> Categories { get; set; }
    }
  1. 类别模型类
public class Category
    {
        [Key]
        public int CatID { get; set; }
        public string CatName { get; set; }
        public string Slug { get; set; }
        public string CatIcon { get; set; }
    }
  1. AddStore视图
@model C4A.Models.VM.Store

@{
    ViewBag.Title = "AddStore";
}

<h2>AddStore</h2>


@using (Html.BeginForm("AddStore","Store",FormMethod.Post,new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true,"",new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.StoreName,htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StoreName,new { htmlAttributes = new { @class = "form-control col-md-12 col-sm-2" } })
                @Html.ValidationMessageFor(model => model.StoreName,new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.MetaDesc,htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.MetaDesc,new { htmlAttributes = new { @class = "form-control col-md-12 col-sm-2" } })
                @Html.ValidationMessageFor(model => model.MetaDesc,new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <label class="control-label col-md-2">Upload Image</label>
            <div class="col-md-10">
                <input type="file" name="file" id="file" class="btn btn-info" />
                @Html.ValidationMessageFor(model => model.StoreLogo,new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TopDesc,htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.TopDesc,new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.TopDesc,new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.MainDesc,htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.MainDesc,new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.MainDesc,new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <label class="control-label col-md-2">Category</label>
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.CatID,Model.Categories,"Select Categories",new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.CatID,new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List","Index")
</div>

@section Scripts {
    <script src="~/Scripts/jquery-3.5.1.min.js"></script>
    @Scripts.Render("~/bundles/jqueryval")

    <script src="~/Scripts/SideBar.js"></script>
    <script src="~/Scripts/ckeditor/ckeditor.js"></script>

    <script>
        CKEDITOR.replace("TopDesc");
        CKEDITOR.replace("MainDesc");
    </script>
}
  1. 控制器
[HttpGet]
        public ActionResult AddStore()
        {
            Store model = new Store();
            using (Db db = new Db())
            {
                model.Categories = new SelectList(db.Categories.ToList(),"CatID","CatName");
            }
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddStore(Store model,HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories = new SelectList(db.Categories.ToList(),"CatName");
                    return View(model);
                }
            }

            using (Db db = new Db())
            {
                if (db.Stores.Any(x => x.StoreName == model.StoreName))
                {
                    ModelState.AddModelError("","Store name already taken");
                    model.Categories = new SelectList(db.Categories.ToList(),"CatName");
                    return View(model);
                }
            }

            int id;

            using (Db db = new Db())
            {
                Store dto = new Store();

                dto.StoreName = model.StoreName;
                //dto.StoreLogo = model.StoreLogo;
                dto.TopDesc = model.TopDesc;
                dto.MainDesc = model.MainDesc;
                dto.CatID = model.CatID;
                dto.Slug = model.StoreName.Replace(" ","-").ToLower();
                dto.MetaDesc = model.MetaDesc;

                Category catDto = db.Categories.FirstOrDefault(x => x.CatID == model.CatID);
                dto.CatName = catDto.CatName;

                db.Stores.Add(dto);
                db.SaveChanges();

                id = dto.StoreID;
            }
            TempData["SM"] = "Store Added Successfully";

            #region Upload Image
            string StoreImageName = Path.GetFileName(file.FileName) + ".webp";
            string physicalPath = Server.MapPath("~/Images/" + StoreImageName);

            if (file != null)
            {
                // Get file extension
                string ext = file.ContentType.ToLower();

                // Verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/webp" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(),"CatName");
                        ModelState.AddModelError("","The image was not uploaded - wrong image extension.");
                        return View(model);
                    }


                }

                // Save image name to DTO
                using (Db db = new Db())
                {
                    Store dto = db.Stores.Find(id);
                    dto.StoreLogo = StoreImageName;

                    db.SaveChanges();
                }
                file.SaveAs(physicalPath);
            }
            #endregion
            return RedirectToAction("AllStore");
        }

有人可以提供代码帮助,以便我可以为特定商店分配多个类别

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-