ASP.NET Модель MVC.Состояние не позволяет сохранять данные в базе данных

#asp.net-mvc #view

Вопрос:

Model.State не читает код try{}catch{} , пропускает прямо в конце»}», и это приводит к тому, что контроллер не может сохранить данные в базе данных, а созданное представление не перенаправляется на главную страницу «индекс» .

Это мой код:

Класс модели Pessoa :

 using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace GesTark.Models
{
    public class Pessoa
    {
        [Key]
        public int PessoaId { get; set; }
    
        [Display(Name = "Foto")]
        [DataType(DataType.ImageUrl)]
        public string Photo { get; set; }
    
        [Display(Name = "Nome Completo")]
        [Required(ErrorMessage = "O Campo {0} é Obrigatório")]
        public string Nome { get; set; }
    
        [DataType(DataType.Date)]
        [Display(Name = "Data de Nascimento")]
        [Required(ErrorMessage = "O Campo {0} é Obrigatório")]
        public string AnoNascimento { get; set; }
    
        //public double Idade { get; set; }
    
        [Display(Name = "Nº de Agente")]
        [Required(ErrorMessage = "O Campo {0} é Obrigatório!")]
        [Index("NumeroAgenteIndex", IsUnique = true)]
        public int NumeroAgente { get; set; }
    
        [DataType(DataType.PhoneNumber)]
        [RegularExpression(@"^(d{9})$", ErrorMessage = "Não é um número de telefone válido!")]
        //[StringLength(maximumLength: 20, ErrorMessage = "Só é permitido 9 ou 20 digitos", MinimumLength = 9)]
        public string Telefone { get; set; }
    
        //[StringLength(100, ErrorMessage = "O Campo {0} pode ter no maximo {1} e minimo {2} caracteres", MinimumLength = 7)]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
    
        [Display(Name ="Vinculo")]
        [StringLength(50, ErrorMessage = "O Campo {0} é Obrigatorio!")]
        public string Activo { get; set; }
    
        [Display(Name = "Gabinetes")]
        //[Required(ErrorMessage = "Escolha o Gabinete em que se encontra")]
        public int GabinetesGabineteId { get; set; }
    
        //[Required(ErrorMessage = "O Campo {0} do Funcionário é Obrigatório!")]
        public string Cargo { get; set; }
    
        [Display(Name = "Categoria")]
        //[Required(ErrorMessage = "Escolha a Categoria em que se encontra")]
        public int NivelNivelId { get; set; }
    
        [DataType(DataType.Date)]
        [Display(Name ="Inicio de Função")]
        public string DataInicio { get; set; }
    
        [DataType(DataType.Date)]
        [Display(Name = "Fim de Comissão")]
        public string DataFim { get; set; }
    
        [Display(Name = "Provincias")]
        [Required(ErrorMessage = "O Campo {0} do Funcionário é Obrigatório!")]
        public string Estados { get; set; }
    
        [Display(Name ="Condição")]
        //[Required(ErrorMessage = "O Campo {0} do Funcionário é Obrigatório!")]
        public string Observacao { get; set; }
    
        public virtual Gabinetes gabojecto { get; set; }
        public virtual Nivel nivelojecto { get; set; }
    
        public ICollection<RelJuridico> Pessoaobjecto { get; set; }
    }
}
 

Класс модели PessoaView :

 using System.Collections.Generic;
using System.Web;

namespace GesTark.Models
{
    public class PessoaView
    {
        public Pessoa Pessoa { get; set; }

        public ArquivosGuardados ArquivosGuardado { get; set; }
        public AssuntoGeral AssuntoGeral { get; set; }
        public Provincia Provincia { get; set; }
        public Gabinetes Gabinetes { get; set; }
        public RelJuridico RelJuridicos { get; set; }

        public HttpPostedFileBase Foto { get; set; }
        public HttpPostedFileBase Ficheiro { get; set; }
        public HttpPostedFileBase File { get; set; }

        public int id { get; set; }
    }
}
 

Контроллер Pessoa :

 public ActionResult Create()
{
    ViewBag.Nivel = new SelectList(db.Nivels, "NivelId", "Nome");
    ViewBag.Gabinetes = new SelectList(db.Gabinetes, "GabineteId", "Nome");
    return View();
}
    
// POST: Pessoas/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PessoaView view)
{
    ViewBag.Nivel = new SelectList(db.Nivels, "NivelId", "Nome", view.Pessoa.NivelNivelId);
    ViewBag.Gabinetes = new SelectList(db.Gabinetes, "GabineteId", "Nome", view.Pessoa.GabinetesGabineteId);
    
    if (ModelState.IsValid)
    {
        db.Pessoas.Add(view.Pessoa);

        try
        {
            db.SaveChanges();

            if (view.Foto != null)
            {
                var pic = Utilidades.UploadPhto(view.Foto);

                if (!string.IsNullOrEmpty(pic))
                {
                    view.Pessoa.Photo = string.Format("~/Content/Fotos/{0}", pic);
                }
            }
    
            return RedirectToAction("Index", "Principal");
        }
        catch (Exception ex)
        {
            ModelState.AddModelError(string.Empty, ex.Message);
        }
    }
    
    return View(view);
    
    // return Json(new { resultado = true, mensagem = "Cadastro com Sucesso!" });
    // else
    // {
    //    IEnumerable<ModelError> erros = ModelState.Values.SelectMany(item => item.Errors);
    //    return Json(new { resultado = false, mensagem = erros });
    // }
}
 

View Pessoa/create :

 @model GesTark.Models.PessoaView

    <h2>Registrar Funcionário</h2>
    
    @using (Html.BeginForm("Create", "Pessoas", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
    
        <div class="row">
            <div class="col-md-6">
                <div class="form-horizontal">
    
                    <hr />
    
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Pessoa.Nome, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Pessoa.Nome, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.AnoNascimento, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Pessoa.AnoNascimento, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Pessoa.Nome, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.NumeroAgente, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Pessoa.NumeroAgente, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Pessoa.NumeroAgente, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.Telefone, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Pessoa.Telefone, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Pessoa.Telefone, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.Email, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Pessoa.Email, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessage("Por favor insira um endereço de e-mail válido.", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.DataInicio, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Pessoa.DataInicio, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Pessoa.DataInicio, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.NivelNivelId, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.Pessoa.NivelNivelId, ViewBag.Nivel as IEnumerable<SelectListItem>, "Selecione uma Categoria", new { @required = "required", @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.Pessoa.NivelNivelId, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.Cargo, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.Pessoa.Cargo, listItems, "Selecione o Cargo", new { @required = "required", @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.Pessoa.Cargo, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.DataFim, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.Pessoa.DataFim, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Pessoa.DataFim, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.Activo, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.Pessoa.Activo, afeto, "Selecione o Status", new { @required = "required", @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.Pessoa.Activo, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.Observacao, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.Pessoa.Observacao, cond, "Selecione a Condição", new { @required = "required", @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.Pessoa.Observacao, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
                    <div class="form-group">
                        @Html.LabelFor(model => model.Pessoa.GabinetesGabineteId, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.DropDownListFor(model => model.Pessoa.GabinetesGabineteId, ViewBag.Gabinetes as IEnumerable<SelectListItem>, "Selecione um Gabinete", new { @required = "required", @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.Pessoa.GabinetesGabineteId, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
    
    
                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                           
                            <button type="submit" class="btn btn-success">Salvar</button> | @Html.ActionLink("Cancelar", "Index", "Principal", null, new { @class = "btn btn-default" })
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.Foto, new { id = "Photo", type = "file" })
                </div>
            </div>
    
        </div>
    }
    
    @section scripts
        {
            @Scripts.Render("~/Bundles/jqueryVal")
        }
 

Отладка начинается здесь, и после того, как она не проверяется, она пропускается до конца, затем не перенаправляется, и представление создает обновления, но сохраняет данные без сохранения.

отладка iniciat

Финал

Комментарии:

1. Можете ли вы также опубликовать свой класс модели, пожалуйста?

2. да, я отредактировал его еще раз. уже поставил

3. Привет, основываясь на вашем снимке экрана для метода [HttpPost] Create(PessoaView view) , у него нет закрывающей скобки } . И в [HttpPost] есть избыточный код Create(PessoaView view) для [HttpPost] Create(PessoaView view) . Пожалуйста, проверьте свой код и перестройте проект, чтобы увидеть любую (синтаксическую) ошибку.

4. все в порядке, я это сделаю. Я скажу кое-что позже