簡體   English   中英

ASP.Net MVC創建寄存器錯誤

[英]ASP.Net MVC Creating a register bug

我有這個東西在我的應用程序上運行。 我有3個表,1個主表和2個創建主表所需的表,主表依賴於2個表,它們與約束連接。 我有主表:Word然后我有另外兩個表:困難和類別。 我創造了難度:輕松然后我創造了類別:自然。 所以現在,我可以用這兩個屬性創建盡可能多的單詞,但它給了我一個錯誤。 如果我創造這種方式,我只能創建一個單詞

Dificulty - > Category - > Word

要么

類別 - >難度 - >單詞

如果沒有這條路,我就無法創造一個詞,我不知道為什么。 這些值存儲在一個數據庫中,該數據庫將在2個ComboBox中調用,1個用於Difficulty,另一個用於Category。 如果我想創建一個單詞,我需要創建一個新類別和一個新的難度,否則它將返回null。

這是我的模型視圖:

public partial class palavra
    {
        public int id_pal { get; set; }
        public Nullable<int> LETRAS { get; set; }
        public string PISTA { get; set; }
        public int id_cat { get; set; }
        public int id_dificuldade { get; set; }
        public string nomepalavra { get; set; }

        public virtual  categoria categoria { get; set; }
       public virtual dificuldade dificuldade { get; set; }
    }

這是我的控制器:

public ActionResult Index()
        {
            var palavras = db.palavras.Include(p => p.categoria).Include(p => p.dificuldade);
           return View(palavras.ToList());
        }



        // GET: palavras/Create
        public ActionResult Create()
        {
            ViewBag.id_cat = new SelectList(db.categorias, "id_cat", "TIPO_CATEGORIA");
            ViewBag.id_dificuldade = new SelectList(db.dificuldades, "id_dificuldade", "TIPO_DIFICULDADE");
            return View();
        }

        // POST: palavras/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "id_pal,LETRAS,PISTA,id_cat,id_dificuldade,nomepalavra")] palavra palavra)
        {
            if (ModelState.IsValid)
            {
                db.palavras.Add(palavra);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.id_cat = new SelectList(db.categorias, "id_cat", "TIPO_CATEGORIA", palavra.id_cat);
            ViewBag.id_dificuldade = new SelectList(db.dificuldades, "id_dificuldade", "TIPO_DIFICULDADE", palavra.id_dificuldade);
            return View(palavra);
        }

這是我的看法:

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.nomepalavra)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LETRAS)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.PISTA)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.categoria.TIPO_CATEGORIA)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.dificuldade.TIPO_DIFICULDADE)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.nomepalavra)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LETRAS)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.PISTA)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.categoria.TIPO_CATEGORIA)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.dificuldade.TIPO_DIFICULDADE)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.id_pal }) |
            @Html.ActionLink("Details", "Details", new { id=item.id_pal }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.id_pal })
        </td>
    </tr>
}

每當我運行我的代碼插入時,我都會收到此錯誤:

EntityFramework.dll中出現“System.Data.Entity.Infrastructure.DbUpdateException”類型的異常,但未在用戶代碼中處理

附加信息:更新條目時發生錯誤。 有關詳細信息,請參閱內部異常

當我檢查詳細信息時,似乎“類別”表和“難度”表為空,但其他字段都包含我給他們的信息。

我的數據庫架構如下:

類別連接到Word,而難度連接到Word。

類別和難度都是與表格Word的1對多關系。

如果您使用實體框架,則需要在模型中定義約束,有2個選項,首先是代碼,或者是數據庫優先

這是我的數據庫第一個例子

數據庫優先

從db生成模型后,使用scaffolding輕松創建create update delete

腳手架crud

使用腳手架更容易創建crud,如果有任何約束

上面的示例您創建了選擇難度/類別的工作是的,您的下拉列表將自動創建

例如我的代碼菜單創建者控制器

   // GET: SystemMenus/Create
    public IActionResult Create()
    {
        ViewData["ParentId"] = new SelectList(_context.SystemMenus, "Id", "Name");      
        ViewData["Color"] = new SelectList(OptionDropdown.GetBackgroundColor(), "Value", "Text");
        ViewData["Size"] = new SelectList(OptionDropdown.GetSize(), "Value", "Text");
        ViewData["Module"] = new SelectList(OptionDropdown.GetModule(), "Value", "Text");
        return View();
    }

    // POST: SystemMenus/Create
    // To protect from overposting attacks, please 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> Create([Bind("Id,Name,Controller,Action,ParentId,Icon,Module,Description,FixHeader,Color,Size")] SystemMenu systemMenu)
    {
        if (ModelState.IsValid)
        {
            _context.Add(systemMenu);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        ViewData["ParentId"] = new SelectList(_context.SystemMenus, "Id", "Name", systemMenu.ParentId);
        ViewData["Color"] = new SelectList(OptionDropdown.GetBackgroundColor(), "Value", "Text", systemMenu.Color);
        ViewData["Size"] = new SelectList(OptionDropdown.GetSize(), "Value", "Text", systemMenu.Size);
        ViewData["Module"] = new SelectList(OptionDropdown.GetModule(), "Value", "Text", systemMenu.Module);
        return View(systemMenu);
    }

在這里我的模型與遞歸約束parentid

 public class SystemMenu
{
    public SystemMenu()
    {
        Details = new HashSet<SystemMenu>();
    }


    [Key]
    public int Id { get; set; }

    [StringLength(50)]
    public string Name { get; set; }

    [StringLength(50)]
    public string Controller { get; set; }
    [StringLength(50)]
    public string Action { get; set; }

    [ForeignKey("ParentId")]

    public SystemMenu Parent { get; set; }
    [Display(Name = "Parent")]
    public int? ParentId { get; set; }
    [StringLength(50)]
    public string Icon { get; set; }

    [StringLength(50)]
    public string Module { get; set; }

    [StringLength(200)]
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }
    public bool FixHeader { get; set; }

    [StringLength(50)]
    public string Color { get; set; }

    [StringLength(50)]
    public string Size { get; set; }

    public ICollection<SystemMenu> Details { get; set; }
}

這是我的看法

enter code 

 @model NCFramework.Models.System.SystemMenu @{ ViewData["Title"] = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; } <div class="row"> <div class="col-md-4"> <form asp-action="Create"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Controller" class="control-label"></label> <input asp-for="Controller" class="form-control" /> <span asp-validation-for="Controller" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Action" class="control-label"></label> <input asp-for="Action" class="form-control" /> <span asp-validation-for="Action" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="ParentId" class="control-label"></label> <select asp-for="ParentId" class ="form-control" asp-items="ViewBag.ParentId"> <option value="">Select</option> </select> </div> <div class="form-group"> <label asp-for="Icon" class="control-label"></label> <input asp-for="Icon" class="form-control" /> <span asp-validation-for="Icon" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Module" class="control-label"></label> <select asp-for="Module" class="form-control" asp-items="ViewBag.Module"> <option value="">Select</option> </select> <span asp-validation-for="Module" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Description" class="control-label"></label> <input asp-for="Description" class="form-control" /> <span asp-validation-for="Description" class="text-danger"></span> </div> <div class="form-group"> <div class="mt-checkbox-list"> <label class="mt-checkbox mt-checkbox-outline"> @Html.DisplayNameFor(model => model.FixHeader) <input asp-for="FixHeader" class="checkbox-inline" /> <span></span> </label> </div> </div> <div class="form-group"> <label asp-for="Color" class="control-label"></label> <select asp-for="Color" class="form-control" asp-items="ViewBag.Color"> <option value="">Select</option> </select> <span asp-validation-for="Color" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Size" class="control-label"></label> <select asp-for="Size" class="form-control" asp-items="ViewBag.Size"> <option value="">Select</option> </select> <span asp-validation-for="Size" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-default" /> </div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } 

這里

使用asp.net核心mvc的例子也可以嘗試使用visual studio,這些3個文件是由腳手架生成的,首先是定義的模型

鋤頭有幫助

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM