【问题标题】:try to send a viewmodel to view尝试发送一个视图模型来查看
【发布时间】:2021-01-23 00:40:19
【问题描述】:

我有一个 asp mvc 项目:

型号:

 public class TeamDto
{
    public int TenantId { get; set; }
    public string Name { get; set; }
    public List<UserListDto> Users { get; set; }
}
    
    public class AddTeamViewModel
    {
        public TeamDto Team { get; set; }
        public List<UserListDto> AllUsers { get; set; }
    }

控制器:

 public async Task<IActionResult> AddOrEditTeam(int id = 0)
        {
            var users = await _userAppService.GetAllUsers();

            var view = new AddTeamViewModel { Team = new TeamDto(), AllUsers = users.ToList() };
            if (id == 0) return View(view);

            var team = await _teamAppService.GetTeamById(id);

            return View(new AddTeamViewModel { AllUsers = users.ToList() , Team = team  });
        }

查看:

  <h4 class="m-portlet__head-caption">@(Model.Team.Id > 0 ? "Edit Team" : "Add Team")</h4>

我无法理解为什么会出现此错误:

处理请求时发生未处理的异常。 NullReferenceException:对象引用未设置为对象的实例。 AspNetCore.Areas_App_Views_Team_AddOrEditTeam.b__22_1()

【问题讨论】:

    标签: asp.net model-view-controller controller


    【解决方案1】:

    您似乎正在发布值,然后尝试将视图模型发送到视图。在这种情况下,请尝试重定向到操作而不是显示视图。

     public async Task<IActionResult> AddOrEditTeam(int id = 0)
            {
                var users = await _userAppService.GetAllUsers();
    
                var view = new AddTeamViewModel { Team = new TeamDto(), AllUsers = users.ToList() };
                if (id == 0) return RedirectToAction("YourViewName",view);
    
                var team = await _teamAppService.GetTeamById(id);
    
                AddTeamViewModel teams = new AddTeamViewModel{
                    AllUsers = users.ToList(), 
                    Team = team
                };
    
                return RedirectToAction("YourViewName", teams);
            }
    
    

    这将解决您的对象引用问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多