【问题标题】:asp net trying to save single column but i keep getting this error - ASP NET MVC 5asp net 试图保存单列,但我不断收到此错误 - ASP NET MVC 5
【发布时间】:2015-09-17 08:37:51
【问题描述】:

当我尝试在 ASP NET MVC 5 中编辑单个列时不断收到此错误

Cannot insert the value NULL into column 'naam', table

这是我的邮政编码

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index([Bind(Include = "id,email")] user user)
    {
        var username = HttpContext.User.Identity.Name;
        if (ModelState.IsValid)
        {
            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(user);
    }

这就是模型

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace LiemersApp.Models.EntityModels
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;

    public partial class profiel
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public profiel()
        {
            this.meldingens = new HashSet<meldingen>();
        }

        public int id { get; set; }
        [DisplayName("Email:")]
        public string email { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<meldingen> meldingens { get; set; }
    }
}

所以我想知道为什么它不起作用,因为我只想将更改保存到电子邮件列任何想法为什么会发生这种情况,因为我无法弄清楚

问候

【问题讨论】:

  • 错误很明显,您需要在名称列中插入值。
  • 您展示的方法适用于user 类,但您展示的模型适用于profiel 类!显示正确的代码。

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


【解决方案1】:

在您的示例中,您不仅仅更改模型中的 name 属性,还映射了控制器中传入和绑定的所有字段。如果您不绑定某些属性,则 null 就像您的字段错误。

您可以像这样更改控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "id,email")] user user)
{
    var username = HttpContext.User.Identity.Name;
    if (ModelState.IsValid)
    {
        var userChange = db.profiels.Single(x => x.id == user.id);
        userChange.email = user.Email;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(user);
}

【讨论】:

    猜你喜欢
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2016-12-16
    • 2016-08-04
    • 1970-01-01
    • 2015-05-08
    相关资源
    最近更新 更多