Элемент модели передан в словарь в asp. net mvc - PullRequest
0 голосов
/ 25 марта 2020

У меня ошибка при выполнении программы. Содержимое ошибки: элемент модели, переданный в словарь, имеет тип 'System.Data.Entity.DynamicProxies.Child_A03B4AB53F9E2ED1CB70F81E60FFA68CF868CF01DE6D2C340D267350F8543009', но для этого словаря требуется модель типа admin. Обратите внимание '.

при выполнении этого представления

   @model adminSection.Models.Note
@{
    ViewBag.Title = "Add_Note";
}

<h2>Add_Note</h2>
@using (Html.BeginForm("Add_Note", "Admin", FormMethod.Post))
{
    <div class="form-horizontal">
        <div class="form-group">
            @Html.LabelFor(x=>x.Note_title,htmlAttributes:new { @class="label-control col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(x => x.Note_title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(x => x.Note_title, null, new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(x => x.Note_title, htmlAttributes: new { @class = "label-control col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(x => x.Note_title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(x => x.Note_title, null, new { @class = "text-danger" })
            </div>
        </div>

    </div>
    <div>
        <input type="submit" value="Add" class="btn btn-default" />
    </div>


}

и мой контроллер

[HttpGet]
    public ActionResult Add_Note(int? id)
    {
        if (Session["ID"] == null)
            return RedirectToAction("Login", "Home");
        else
        {
            if (id == null)
            {
                return HttpNotFound();
            }
            else
            {
                using (Context db = new Context())
                {
                    var child = db.child.Find(id);
                    if (child == null)
                    {
                        return HttpNotFound();
                    }
                    else
                    {
                        return View(child);
                    }

                }


        }
    }
}
[HttpPost]
public ActionResult Add_Note(Note note, Child child)
{
    if (ModelState.IsValid)
    {
        note.Child_id = child.Chi_Id;
        note.Note_Date = DateTime.Now;
        child.note = new List<Note>();

        db.Entry(child).State = EntityState.Modified;
        var admin = db.admin.Find(Session["Id"]);
        if (admin != null)
        {
            if (admin.Adm_Name == Session["Name"].ToString())
            {
                admin.note = new List<Note>();
                admin.note.Add(note);
                db.Entry(admin).State = EntityState.Modified;
                note.admin = admin;
                //db.SaveChanges();
            }
        }
        else
        {
            return HttpNotFound();
        }
    }

    child.note.Add(note);
    note.child = child;
    db.note.Add(note);
    db.SaveChanges();
    return RedirectToAction("Home", "Admin");
}

и мой дочерний класс

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

    namespace adminSection.Models
    {
        [Table("tbl_child")]
        public partial class Child
        {
            [Key]
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int Chi_Id { get; set; }
            /// <summary>
            /// child Id att
            /// </summary>
            [Required(ErrorMessage ="you must provied child first name")]
            [Display(Name ="Child First Name")]
            public string  Chi_First_Name { get; set; }
            /// <summary>
            /// First name att
            /// </summary>
            [Required(ErrorMessage ="you must provied child last Name")]
            [Display(Name ="Child Last Name")]
            public string Chi_Last_Name { get; set; }
            /// <summary>
            /// Last Name Att
            /// </summary>
            [Required(ErrorMessage ="you must provied child age")]
            [Display(Name ="Child Age")]
            [Range(0,18, ErrorMessage = "Correct Input")]
            public int Age { get; set; }
            /// <summary>
            /// Child Age Att
            /// </summary>
            [Required(ErrorMessage ="you must provied child gender")]
            [Display(Name ="Child Gender")]
            public string Gender { get; set; }
            /// <summary>
            /// Child Gender Att
            /// </summary>
            [Display(

Name ="Child School")]
        public string Chi_School { get; set; }
        /// <summary>
        /// Child School
        /// </summary>

        [Required(ErrorMessage ="you must provied parent status")]
        [Display(Name ="Child Parent Status")]
        public string Chi_parent_status { get; set; }
        /// <summary>
        /// Child Parent Status
        /// </summary>
        /// 
        [Display(Name ="Child Image Path")]
        public string Chi_Image_Path { get; set; }
        /// <summary>
        /// Child Image Status
        /// </summary>
        ///


        public virtual Admin admin { get; set; }
        public int Adm_ID { get; set; }

        public virtual Parent parent { get; set; }
        public int Par_ID { get; set; }


        public  ICollection<Note> note { get; set; }


    }
}

и мой записка класса

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

namespace adminSection.Models
{
    [Table("tbl_Note")]
    public class Note
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        [ScaffoldColumn(false)]
        public int Note_Id { get; set; }
        /// <summary>
        /// note id end
        /// </summary>
        [Required(ErrorMessage ="You must provide this note title")]
        [Display(Name ="Header")]
        public string Note_title { get; set; }
        /// <summary>
        /// note of title end
        /// </summary>

        [Required(ErrorMessage ="You must provide note content")]
        [Display(Name = "content")]
        public string note_content { get; set; }
        /// <summary>
        /// 
        ///Note Content end
        /// </summary>
        public DateTime Note_Date { get; set; }

        /// <summary>
        /// Date Of note here
        /// </summary>
        public virtual Child child { get; set; }
        public int Child_id { get; set; }
        // note with Child ont to many 

        public virtual Admin admin { get; set; }
        public int Admin_id { get; set; }
        // Note with Admin and note is many to one

        public virtual Parent parent { get; set; }

        public int Parent_Id { get; set; }
        // Note with Parent and note is many to one
    }
}

1 Ответ

0 голосов
/ 25 марта 2020

Я думаю, что использование типа объекта (может быть Примечание) вместо var в var child = db.child.Find(id) решает вашу проблему.

...