【问题标题】:Can't show any property of the category of the todo task无法显示待办任务类别的任何属性
【发布时间】:2022-01-15 17:43:18
【问题描述】:

我有一个简单的 asp.net 核心项目,在项目中,任务页面应该显示任务的详细信息 - 包括任务的类别 - 但发生的事情是任务的类别和用户的用户名没有显示索引页。 这是我在 github 上的存储库链接:https://github.com/mohamedvoli/ToDo/tree/main/TodoList 这是我的索引视图:


@model IEnumerable<TodoList.Models.TodoTask>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Add A New Task</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Title)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Description)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TimeStamp)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ParentCategory.Title)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.User.UserName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.IsDone)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.TimeStamp)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ParentCategory.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.User.UserName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.IsDone)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.TodoTaskId">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.TodoTaskId">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.TodoTaskId">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

这是我的控制器:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TodoList.Models;
using TodoList.Models.Repos;
using TodoList.Models.ViewModels;

namespace TodoList.Controllers
{
    public class TodoTasksController : Controller
    {
        private ITodoRepo<TodoTask> _TaskRepo;
        private ITodoRepo<Category> _CategoryRepo;
        private UserManager<ApplicationUser> _UserManager;
        public TodoTasksController(ITodoRepo<TodoTask> TaskRepo,
            UserManager<ApplicationUser> UserManager,
            ITodoRepo<Category> CategoryRepo)
        {
            _TaskRepo = TaskRepo;
            _UserManager = UserManager;
            _CategoryRepo = CategoryRepo;
        }

        // GET: TodoTasksController
        [Authorize]
        public ActionResult Index(string SearchingTerm)
        {
            var UserId = _UserManager.GetUserId(User);
            List<TodoTask> AllTasks = _TaskRepo.List(UserId);
            if (!string.IsNullOrEmpty(SearchingTerm))
            {
                AllTasks = _TaskRepo.Search(SearchingTerm, UserId);
            }
            return View(AllTasks);
        }

        // GET: TodoTasksController/Details/5
        [Authorize]
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: TodoTasksController/Create
        [Authorize]
        public ActionResult Create()
        {
            return View(SetTheModelToGetMethod());
        }

        // POST: TodoTasksController/Create
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> CreateAsync(TaskCategoryVm model)
        {

            var UserId = _UserManager.GetUserId(User);
            if (ModelState.IsValid)
            {
                try
                {
                    if (model.CategoryId == -1)
                    {
                        ViewData["Message"] = "Please select a category!"; 
                        return View(SetTheModelToGetMethod());
                    }
                    else
                    {
                        var category = _CategoryRepo.Find(model.CategoryId);
                        var User = await _UserManager.FindByIdAsync(UserId);
                        TodoTask ValidModel = new TodoTask
                        {
                            Title = model.Title,
                            Description = model.Description,
                            TimeStamp = DateTime.Now,
                            IsDone = model.IsDone,
                            ParentCategory = category,
                            User = User
                        };
                        _TaskRepo.Add(ValidModel);
                        return RedirectToAction(nameof(Index));
                    }
                }
                catch
                {
                    return View();
                }
            }
            else
            {
                ModelState.AddModelError("", "You have to fill all the required fields!");
                return View(FillInSelectList(UserId));
            }
        }

        // GET: TodoTasksController/Edit/5
        [Authorize]
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: TodoTasksController/Edit/5
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: TodoTasksController/Delete/5
        [Authorize]
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: TodoTasksController/Delete/5
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
        [Authorize]
        public List<Category> FillInSelectList(string UserId)
        {
            var AllCategories = _CategoryRepo.List(UserId).ToList();
            AllCategories.Insert(0, new Category { CategoryId = -1, Title = "--- Please select a category ---" });
            return AllCategories;
        }
        public TaskCategoryVm SetTheModelToGetMethod()
        {
            var UserId = _UserManager.GetUserId(User);
            var AllCategories = FillInSelectList(UserId);
            TaskCategoryVm model = new TaskCategoryVm
            {
                UserId = UserId,
                Categories = AllCategories
            };
            return model;
        }
    }
}

这是我的模型:

using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace TodoList.Models
{
    public class TodoTask
    {
        public int TodoTaskId { get; set; }
        [Required]
        public string Title { get; set; }
        [Required]
        public string Description { get; set; }
        [BindNever]
        public DateTime TimeStamp { get; set; }
        public bool IsDone { get; set; }
        [Required]
        public int CategoryId { get; set; }
        public Category ParentCategory { get; set; }
        public string UserId { get; set; }
        public ApplicationUser User { get; set; }

    }
}

有人可以帮忙吗? 提前致谢。

【问题讨论】:

  • 我相信,如果您将视图中的模型从 IEnumerable 更改为 List,它将起作用。将 IEnumerable 建模为 List
  • 我试过了,但出现了很多错误
  • 您可以尝试构建一个 ViewModel 并从那里继续前进
  • 您是否检查过 ParentCategory 和 User 属性是否分配了值?
  • 请不要在每个动作的顶部使用 [Authorize],只需在控制器类的顶部使用它

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


【解决方案1】:

使用.Include()访问与您的表有关系的表的数据 转到第 41 行的 TaskRepo.cs 用我的代码替换您的函数

public List<TodoTask> List(string id)
    {
        var AllTasks = _db.Tasks.Where(x => x.UserId == id).Include(x=>x.ParentCategory).Include(x=>x.User).ToList();

        return AllTasks;
    }

请修复您在其他功能中没有使用.Include()的其他查询 如需更多使用.Include()的帮助,请访问此链接Click Here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多