【问题标题】:The model item passed into the ViewDataDictionary is of type '...', but this ViewDataDictionary instance requires a model item of type '...'传递给 ViewDataDictionary 的模型项的类型为“...”,但此 ViewDataDictionary 实例需要一个“...”类型的模型项
【发布时间】:2022-02-07 04:21:29
【问题描述】:

我在做什么?
我正在尝试在一个视图中使用两个模态。

有什么问题?
运行时出现此错误:

An unhandled exception occurred while processing the request.
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ProgramaEstagio.Models.Person', but this ViewDataDictionary instance requires a model item of type 'ProgramaEstagio.Models.RegisterViewModel'.

Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary.EnsureCompatible(object value)

“PersonController.cs”的一部分:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ProgramaEstagio.Data;
using ProgramaEstagio.Models;

namespace ProgramaEstagio.Controllers
{
    public class PersonController : Controller
    {
        private readonly ApplicationDbContext _context;

        public PersonController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Person
        public async Task<IActionResult> Index()
        {
            return View(await _context.Person.ToListAsync());
        }
        // GET: Person/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var person = await _context.Person.FindAsync(id);
            if (person == null)
            {
                return NotFound();
            }
            return View(person);
        }

        // POST: Person/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,FullName,BirthDate,sex")] Person person)
        {
            if (id != person.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(person);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PersonExists(person.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(person);
        }

RegisterViewModel.cs:

namespace ProgramaEstagio.Models
{
    public class RegisterViewModel
    {
        public Person Person { get; set; }
        public Address Address { get; set; }
    }
}

Edit.cshtml:

@model ProgramaEstagio.Models.RegisterViewModel

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

<h1>Edit</h1>

<h4>Person</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Person.ID" />
            <div class="form-group">
                <label asp-for="Person.FullName" class="control-label"></label>
                <input asp-for="Person.FullName" class="form-control" />
                <span asp-validation-for="Person.FullName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Person.BirthDate" class="control-label"></label>
                <input asp-for="Person.BirthDate" class="form-control" />
                <span asp-validation-for="Person.BirthDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Person.sex" class="control-label"></label>
                <input asp-for="Person.sex" class="form-control" />
                <span asp-validation-for="Person.sex" class="text-danger"></span>
            </div>

            <h4>Address</h4>
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Address.ID" />
            <div class="form-group">
                <label asp-for="Address.Country" class="control-label"></label>
                <input asp-for="Address.Country" class="form-control" />
                <span asp-validation-for="Address.Country" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address.Complement" class="control-label"></label>
                <input asp-for="Address.Complement" class="form-control" />
                <span asp-validation-for="Address.Complement" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address.Distric" class="control-label"></label>
                <input asp-for="Address.Distric" class="form-control" />
                <span asp-validation-for="Address.Distric" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address.City" class="control-label"></label>
                <input asp-for="Address.City" class="form-control" />
                <span asp-validation-for="Address.City" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address.State" class="control-label"></label>
                <input asp-for="Address.State" class="form-control" />
                <span asp-validation-for="Address.State" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address.PersonID" class="control-label"></label>
                <select asp-for="Address.PersonID" class="form-control" asp-items="ViewBag.PersonID"></select>
                <span asp-validation-for="Address.PersonID" class="text-danger"></span>
            </div>

            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

我必须做什么?请帮我。如果需要更多信息,请询问。对于我正在学习英语的任何拼写和语法错误,我深表歉意。 项目链接:https://github.com/vitorhugo1207/Sys-Vacina/tree/EditPagePersonAdress

编辑: AddressController.cs:

        // GET: Addresse/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            RegisterViewModel register = new RegisterViewModel();
            if (id == null)
            {
                return NotFound();
            }

            var address = await _context.Address.FindAsync(id);
            if (address == null)
            {
                return NotFound();
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            register.Address = address;
            return View(register);
        }

        // POST: Addresse/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,Country,Complement,Distric,City,State,PersonID")] Address address)
        {
            if (id != address.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(address);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!AddressExists(address.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["PersonID"] = new SelectList(_context.Person, "ID", "FullName", address.PersonID);
            return View(address);
        }

【问题讨论】:

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


    【解决方案1】:

    它发生在这条线上:return View(person);。您发送的是 Person 类型的 Model,但您需要发送 RegisterViewModel 的 Model。您需要将正确的Model 发送到您的View

        public async Task<IActionResult> Edit(int? id)
        {
            RegisterViewModel register = new RegisterViewModel();
            if (id == null)
            {
                return NotFound();
            }
    
            var person = await _context.Person.FindAsync(id);
            if (person == null)
            {
                return NotFound();
            }
            register.Person = person;
            var address = await _context.Address.FindAsync(id);
            if (address == null)
            {
                return NotFound();
            }
            register.Address = address;
            return View(register);
        }
    

    【讨论】:

    • 它不会将数据返回到地址字段,仅适用于人员。有办法同时退货吗?
    • @IkkiArtz 获取Address 字段的逻辑是什么?您需要定义获取地址的逻辑,然后将其设置为register.Address
    • 我有疑问。我应该在 return 之前在PersonController 中调用AddressController,或者在PersonController 中创建一个函数来获取数据?我应该怎么做?感谢您的帮助。
    • @IkkiArtz 您可以创建一个数据访问层,您可以根据自己的上下文从中获取数据。您需要展示更多关于如何获取Person 数据以及Person 模型的结构的代码。
    • 我将分支推送到 GitHub,因为这里会变得杂乱无章。链接:github.com/vitorhugo1207/Sys-Vacina/tree/EditPagePersonAdress
    【解决方案2】:

    当你写下这段代码时,你实质上向 C# 做出了一个承诺,即你会发送一个 RegisterViewModel 类型的模型:

    @model ProgramaEstagio.Models.RegisterViewModel
    

    但是你实际上发送了一个人:

    var person = await _context.Person.FindAsync(id);
    ...
    return View(person);
    

    这两件事是什么并不重要,只要他们同意;如果您在一个地方升级/更改类型(如 cshtml),则必须在其他任何地方更改它(如控制器 View(..) 调用)以确保它们彼此保持一致

    【讨论】:

    • 它不会将数据返回到地址字段,仅适用于人员。有办法同时退货吗?
    • 你做一个 registerviewmodel,你把人和地址放在 registerviewmodel 中,然后你返回 registerviewmodel
    猜你喜欢
    • 2020-10-20
    • 2020-10-03
    • 2018-12-25
    • 2022-01-27
    • 2022-06-27
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多