如何在ASP.NET站点中实现用户直接创建并关联新分类的功能
自定义分类关联绑定实现方案
你当前的项目已经实现了基础的分分类文件上传、下载、删除、预览能力,要支持动态新增分类,可以按照以下步骤修改:
现有代码梳理
索引页视图代码
@model IEnumerable<Proiect2PracticaClona.Models.Files> <center> <h1>Suntem fericiti</h1> <h2>Ca ne merge proiectu</h2> <hr /> @if (User.IsInRole("Admin")) { <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index"> <input type="file" name="fifile" /> <div>Alegeti categoria de skill pentru care doriti sa uploadati</div> <div>@Html.RadioButton("category", "incepator", "all")<label>Incepatori</label></div> <div>@Html.RadioButton("category", "intermediar", "all")<label>Intermediari</label></div> <div>@Html.RadioButton("category", "admin", "all")<label>Admini</label></div> <input type="submit" value="Uploadati" /> <hr /> </form>} <div> File Name:<input id="search" onkeyup="search()" placeholder="cauta"/> </div> <table class="table"> <tr> <th>Alegeti Categoria:</th> <th class="active">@Html.ActionLink("Incepator", "Index", "Home", new { id = "incepator" })</th> <th class="active">@Html.ActionLink("Intermediar", "Index", "Home", new { id = "intermediar" })</th> <th class="active">@Html.ActionLink("Admin", "Index", "Home", new { id = "admin" })</th> </tr> <tr> <th>File Name</th> </tr> @foreach (var item in Model) { <tr> <td><a href="/Home/DocumentViewer/@item.info">@item.info</a></td> <td><a href="@Url.Action("Download","Home",new { filename=item.info })">Download</a></td> @if (User.IsInRole("Admin")) { <td><a href="@Url.Action("Delete", "Home", new { id = item.id })">Delete</a></td> } </tr> } </table> @section scripts { <script> function search() { $("tr").each(function (index, value) { if (index > 0 && !$(this).find("td")[0].innerText.toLowerCase().includes($("#search").val().toLowerCase())) { $(this).attr("hidden", true); } else { $(this).removeAttr("hidden"); } console.log(value); }) } </script> } </center>
控制器上传Action代码
[HttpPost] public async Task<IActionResult> Index(IFormFile fifile, string category) { Category.category.Add(category); var fisave = Path.Combine(_iweb.WebRootPath, "Uploads", fifile.FileName); var stream = new FileStream(fisave, FileMode.Create); await fifile.CopyToAsync(stream); Files fileModel=new Files() { info = fifile.FileName, category = category }; _fileRepository.AddFile(fileModel); stream.Close(); files = _fileRepository.GetFileList(); return RedirectToAction("Index",files); }
修改步骤
1. 调整数据存储逻辑
你当前用的静态Category.category存储分类是临时的,服务重启就会丢失,先创建独立的分类表存储结构:
- 新增
Category实体类,包含Id(主键)、CategoryName(分类名称)两个字段 - 配套增加对应的仓储操作方法:
AddCategory(新增分类)、GetAllCategories(获取全部分类) - 把原有三个默认分类先初始化到分类表中
2. 修改Index的GET Action
在返回视图前把全部分类列表传递到视图:
public IActionResult Index(string id = "") { // 原有文件筛选逻辑保留 var files = string.IsNullOrEmpty(id) ? _fileRepository.GetFileList() : _fileRepository.GetFileList().Where(f=>f.category == id).ToList(); // 传递分类列表到视图 ViewBag.AllCategories = _categoryRepository.GetAllCategories(); return View(files); }
3. 新增创建分类的控制器Action
[HttpPost] public IActionResult CreateCategory(string newCategoryName) { if(!User.IsInRole("Admin")) return Forbid(); // 查重,避免重复创建 if(!_categoryRepository.GetAllCategories().Any(c=>c.CategoryName.Equals(newCategoryName, StringComparison.OrdinalIgnoreCase))) { _categoryRepository.AddCategory(new Category { CategoryName = newCategoryName }); } return RedirectToAction("Index"); }
4. 修改视图代码,替换硬编码分类
- 首先在上传表单里新增分类创建入口,同时把原来硬编码的单选框改成循环输出动态分类:
@if (User.IsInRole("Admin")) { <!-- 新增分类表单 --> <form method="post" asp-controller="Home" asp-action="CreateCategory" class="mb-3"> <input type="text" name="newCategoryName" placeholder="输入新分类名称" required /> <input type="submit" value="新增分类" /> <hr /> </form> <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index"> <input type="file" name="fifile" required /> <div>Alegeti categoria de skill pentru care doriti sa uploadati</div> <!-- 动态输出分类单选 --> @foreach(var cate in ViewBag.AllCategories) { <div>@Html.RadioButton("category", cate.CategoryName, ViewBag.AllCategories[0] == cate)<label>@cate.CategoryName</label></div> } <input type="submit" value="Uploadati" /> <hr /> </form> }
- 然后把分类筛选的表头也改成动态循环:
<tr> <th>Alegeti Categoria:</th> <th class="active">@Html.ActionLink("全部", "Index", "Home")</th> @foreach(var cate in ViewBag.AllCategories) { <th class="active">@Html.ActionLink(cate.CategoryName, "Index", "Home", new { id = cate.CategoryName })</th> } </tr>
其他注意点
原来的上传表单里的methord拼写错误,已经在上面的代码里修正为method,否则表单提交会不生效。
内容的提问来源于stack exchange,提问作者Panait Rares Horia
相关产品推荐
相关产品推荐

