【问题标题】:ModelState auto adding errors?ModelState 自动添加错误?
【发布时间】:2009-12-14 18:54:50
【问题描述】:

我有一个控制器应该将一个人添加到数据库中,但是在表单中我有两种人的字段并且只应该添加一个,然后当我发布它时验证它是否是 pf(类型 1)或 pj (类型 2)人,然后我根据人的类型进行验证,没关系,但即使我没有添加任何错误,因为表单已完全输入,我也会从其他字段中得到错误,但是我没有说在任何地方都需要它们,为什么mvc会添加这样的错误?更奇怪的是,自动错误会根据我输入的字段数量而变化,它们可能与我输入的表单有关吗?我不明白发生了什么,求助!!!

我的代码文件:

Pessoa.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarvalhoRodrigues.Domain.Repositories.Cadastro;

namespace CarvalhoRodrigues.Domain.Cadastro
{
    public class Pessoa
    {
        public Pessoa()
        {
            this.Endereco = new List<Endereco>();
        }

        public virtual long Id { get; set; }
        public enum TipoPessoa { Fisica, Juridica }
        public virtual TipoPessoa Tipo { get; set; }
        public virtual ICollection<Endereco> Endereco { get; set; }

    }
}

PessoaFisica.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CarvalhoRodrigues.Domain.Cadastro
{
    public class PessoaFisica : Pessoa
    {
        public PessoaFisica()
            : base()
        {
            this.Tipo = Pessoa.TipoPessoa.Fisica;
        }
        public virtual string CPF { get; set; }
        public virtual string Nome { get; set; }
        public virtual string Sexo { get; set; }
        public virtual DateTime DataNascimento { get; set; }
        public virtual string RG { get; set; }
        public virtual string RGOrgaoExpedidor { get; set; }
        public virtual DateTime RGDataExpedicao { get; set; }
        public virtual string Pai { get; set; }
        public virtual string Mae { get; set; }
    }
}

PessoaJuridica.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CarvalhoRodrigues.Domain.Cadastro
{
    public class PessoaJuridica : Pessoa
    {
        public PessoaJuridica()
            : base()
        {
            this.Tipo = Pessoa.TipoPessoa.Juridica;
            this.Representantes = new List<Pessoa>();
        }

        public virtual string CNPJ { get; set; }
        public virtual string RazaoSocial { get; set; }
        public virtual DateTime DataConstituicao { get; set; }
        public virtual string NomeFantasia { get; set; }
        public virtual ICollection<Pessoa> Representantes { get; set; }
    }
}

Inserir.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Inserir
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" src="../../Scripts/carvalhorodrigues-cadastro.js"></script>
<% using (Html.BeginForm())
   { %>
<h2>Inserir Cliente</h2>
<%= Html.ValidationSummary() %>
<fieldset>
    <legend>Tipo de Pessoa</legend>
    <div>
        <%= Html.RadioButton("TipoPessoa", "PF", true, new { @class = "TipoPessoa" })%> Pessoa Física
        <%= Html.RadioButton("TipoPessoa", "PJ", false, new { @class = "TipoPessoa" })%> Pessoa Jurídica
    </div>
</fieldset>

<fieldset>
    <legend>Dados de Cadastro</legend>
    <div id="PF">
        <p>
        <label for="pf.Nome">Nome:</label> <br />
        <%= Html.TextBox("pf.Nome")%> <%= Html.ValidationMessage("pf.Nome", "*")%>
        </p>

        <p>
        <label for="pf.CPF">CPF:</label> <br />
        <%= Html.TextBox("pf.CPF")%> <%= Html.ValidationMessage("pf.CPF", "*")%>
        </p>

        <p>
        <label for="pf.Sexo">Sexo:</label> <br />
        <%= Html.RadioButton("pf.Sexo", "Masculino", true) %> Masculino
        <%= Html.RadioButton("pf.Sexo", "Feminino")%> Feminino
        </p>

        <p>
        <label for="pf.DataNascimento">Data de Nascimento:</label> <br />
        <%= Html.TextBox("pf.DataNascimento")%> <%= Html.ValidationMessage("pf.DataNascimento", "*")%>
        </p>

        <p>
        <label for="pf.RG">RG:</label> <br />
        <%= Html.TextBox("pf.RG")%> <%= Html.ValidationMessage("pf.RG", "*")%>
        </p>

        <p>
        <label for="pf.RGOrgaoExpedidor">Órgão Expedidor:</label> <br />
        <%= Html.TextBox("pf.RGOrgaoExpedidor")%> <%= Html.ValidationMessage("pf.RGOrgaoExpedidor", "*")%>
        </p>

        <p>
        <label for="pf.RGDataExpedicao">Data de Expedição:</label> <br />
        <%= Html.TextBox("pf.RGDataExpedicao")%> <%= Html.ValidationMessage("pf.RGDataExpedicao", "*")%>
        </p>

        <p>
        <label for="pf.Pai">Pai:</label> <br />
        <%= Html.TextBox("pf.Pai")%> <%= Html.ValidationMessage("pf.Pai", "*")%>
        </p>

        <p>
        <label for="pf.Mae">Mãe:</label> <br />
        <%= Html.TextBox("pf.Mae")%> <%= Html.ValidationMessage("pf.Mae", "*")%>
        </p>
    </div>

    <div id="PJ">
        <p>
        <label for="pj.RazaoSocial">Razão Social:</label> <br />
        <%= Html.TextBox("pj.RazaoSocial")%> <%= Html.ValidationMessage("pj.RazaoSocial", "*")%>
        </p>

        <p>
        <label for="pj.CNPJ">CNPJ:</label> <br />
        <%= Html.TextBox("pj.CNPJ")%> <%= Html.ValidationMessage("pj.CNPJ", "*")%>
        </p>

        <p>
        <label for="pj.NomeFantasia">Nome Fantasia:</label> <br />
        <%= Html.TextBox("pj.NomeFantasia")%> <%= Html.ValidationMessage("pj.NomeFantasia", "*")%>
        </p>

        <p>
        <label for="pj.DataConstituicao">Data de Constituição:</label> <br />
        <%= Html.TextBox("pj.DataConstituicao")%> <%= Html.ValidationMessage("pj.DataConstituicao", "*")%>
        </p>
    </div>
</fieldset>
<input type="submit" value="Cadastrar" />
<% } %>

ClientesController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using CarvalhoRodrigues.Domain.Cadastro;
using CarvalhoRodrigues.Domain.Repositories.Cadastro;

namespace CarvalhoRodrigues.Controllers
{
    public class ClientesController : Controller
    {
        // GET: /clientes/
        public ActionResult Index()
        {
            return View();
        }

        // GET: /clientes/inserir/
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Inserir()
        {
            return View();
        }

        // POST: /clientes/inserir/
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Inserir(string TipoPessoa, [Bind(Exclude = "Id", Prefix="pf")]PessoaFisica pf, [Bind(Exclude = "Id", Prefix="pj")]PessoaJuridica pj)
        {
            IPessoaRepository repository = new PessoaRepository();

            if (TipoPessoa == "PF")
            {
                pf.Tipo = Pessoa.TipoPessoa.Fisica;

                if (pf.Nome == "")
                    ModelState.AddModelError("pf.Nome", "Nome não informado");
                if (pf.CPF == "")
                    ModelState.AddModelError("pf.CPF", "CPF não informado");
                if (pf.DataNascimento == new DateTime())
                    ModelState.AddModelError("pf.DataNascimento", "Data de nascimento não informada");
                if (pf.RG == "")
                    ModelState.AddModelError("pf.RG", "RG não informado");
                if (pf.RGOrgaoExpedidor == "")
                    ModelState.AddModelError("pf.RGOrgaoExpedidor", "Órgão expedidor não informado");
                if (pf.RGDataExpedicao == new DateTime())
                    ModelState.AddModelError("pf.RGDataExpedicao", "Data de expedição não informada");
            }
            else if (TipoPessoa == "PJ")
            {
                if (pj.RazaoSocial == "")
                    ModelState.AddModelError("pj.RazaoSocial", "Razão social não informada");
                if (pj.CNPJ == "")
                    ModelState.AddModelError("pj.CNPJ", "CNPJ não informado");
                if (pj.DataConstituicao == new DateTime())
                    ModelState.AddModelError("pj.DataConstituicao", "Data de constituição não informada");
            }

            if (ModelState.IsValid)
            {
                if (TipoPessoa == "PF")
                    repository.Inserir(pf);
                else if (TipoPessoa == "PJ")
                    repository.Inserir(pj);
            }

            return View();
        }
}

如果我没有在选择“PF”单选的情况下键入任何字段,则会收到以下错误:

  • CPF não 信息
  • Nome não informado
  • 需要一个值。
  • Data de nascimento não informada
  • RG não 信息
  • Órgão expedidor não informado
  • 需要一个值。
  • Data de expedição não informada
  • 需要一个值。

当我认为它应该只是:

  • CPF não 信息
  • Nome não informado
  • Data de nascimento não informada
  • RG não 信息
  • Órgão expedidor não informado
  • Data de expedição não informada

如果我输入所有 PF 字段,我只会收到一个错误:

  • 需要一个值。

消息没有说明错误的来源。我的模型类只是获取和设置,我使用的是 Nhibernate,它们没有任何逻辑,也没有任何必需的字段。

帮助 guyz,我不明白 ModelState 发生了什么。

【问题讨论】:

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


    【解决方案1】:

    您可能在某处有一个非 NULL 字段。 “A value is required”错误是下层添加的。

    如果它未定义为自动编号(身份规范)或未从您的代码中设置的其他列,则它可能是主键。

    【讨论】:

    • 那么,在我添加我的错误之前,我可以重置这个“下层”触发的所有错误吗?感谢您的回复,我仍然无法理解(PJ 字段是非 NULL,但为什么我只得到一个“需要值”仍然是个谜,应该是 3)但它已经很亮了!拥抱!
    • 或者更好,应该是零,我在debug中看了一下,pj的所有字段都不为空,它们有空值,但不为空。
    • "我可以重置..." :可能不是,我认为 a) 您验证为 OK,b) 数据上下文尝试更新数据库,并且映射层或数据库给出此错误.
    • 谢谢伙计,实际上发生的事情是我有一些 DateTime 字段并且在我的模型中它们不可为空,当我发布它时,字符串字段得到一个空字符串,但模型绑定器没有给出一个“空日期”,它在模型状态中引发错误,我解决了它将我的 DateTime 属性更改为 DateTime?,现在它忽略了内置模型绑定器中的 DateTime 属性,这不是我想要的,但它正在工作。谢谢你的评论,它让我明白发生了什么。拥抱!
    猜你喜欢
    • 2018-06-21
    • 1970-01-01
    • 2017-11-02
    • 2011-03-10
    • 2015-07-25
    • 1970-01-01
    • 2021-01-12
    • 2017-11-01
    • 2013-07-11
    相关资源
    最近更新 更多