简体   繁体   English

ASP.NET MVC中的模型ID属性null c#

[英]Model ID property null in ASP.NET MVC c#

I have a model expense 我有模特费用

public class Expense
{
     public int expenseID {get;set;}
     public string expenseName {get;set;}
     public int reportID {get;set;}
}

I have a controller method which should pass an expense object to the view 我有一个控制器方法,应该将费用对象传递给视图

public ActionResult Create(int reportID)
{
    Expense ex = new Expense(){ 
        reportID = reportID
    };
    return View(ex);
}

Then in the view the user can set the expenseName property and I have included 然后在视图中,用户可以设置expenseName属性,我已经包含了

@Html.HiddenFor(model => model.expenseID)
@Html.HiddenFor(model => model.reportID)

Then another controller method accepts the Expense model and should save it to the database however the expenseID is null and a database error occurs This is the controller method 然后另一个控制器方法接受Expense模型并应将其保存到数据库但是expenseID为null并且发生数据库错误这是控制器方法

public ActionResult Create(Expense ex)
{
    if(ModelState.IsValid)
    {
        db.Expenses.Add(ex);
        db.SaveChanges();
        return RedirectToAction("Index");
   }
   return View(ex);
}

Can anyone suggest why the expenseID property is null when we try and add expense to our database thanks! 当我们尝试将费用添加到我们的数据库时,有人可以建议为什么expenseID属性为null谢谢!

expenseID property is null. expenseID属性为null。 Because You setting property expenseID not null and you insert expenseID = null in database => error. 因为您将属性expenseID设置为null并且在database => error中插入expenseID = null。 And model expense you need update again same that: 和模型费用你需要再次更新相同:

public class Expense
{
     [Key]
     public int expenseID {get;set;}
     public string expenseName {get;set;}
     public int reportID {get;set;}
}

And Property expenseID in database if you don't setting "Identity Specification" => expenseID don't auto have new key ID. 如果不设置“Identity Specification”=> expenseID,则数据库中的属性expenseID不会自动拥有新的密钥ID。

Make sure the HiddenFor properties are within your BeginForm using statement: 确保HiddenFor属性在您的BeginForm中使用语句:

@using (Html.BeginForm("Create", "YourController", FormMethod.Post))
{
    @Html.HiddenFor(model => model.expenseID)
    @Html.HiddenFor(model => model.reportID)

    <input class="btn btn-default" type="submit" value="Post Data">
}

Have you set a breakpoint on the Create Action Method to make sure that the Expense model is definitely not null itself when it arrives, if its not then my above suggestion should fix it. 您是否在创建操作方法上设置了一个断点,以确保Expense模型在到达时绝对不是null,如果不是那么我的上述建议应该修复它。

edit This is assuming your ID is populated when you pass it out to your view in the first place, and is not yet to be actually created in the db as Linh Tuan suggested. 编辑这是假设您的ID在首先传递给您的视图时已填充,并且尚未在Linh Tuan建议的数据库中实际创建。

If you are using EF, you should make sure your config is something like this: 如果您使用EF,您应该确保您的配置是这样的:

public ExpenseConfiguration()
{
    HasKey(x => x.expenseId);
}

You should check the Design of that table, and see whether Identity Specification is set to true, if it is, it doesn't matter whether the expenseId is null all the way to INSERT, the db will assign it an incrementing ID once it get to the point of insert. 你应该检查那个表的设计,看看Identity Specification是否设置为true,如果是, expenseId是否expenseId是空的expenseId ,一旦获得,db将为它分配一个递增的ID到插入点。

Your GET method seems to be expecting a reportId as a parameter, could you tell us what is feeding this ActionMethod in the first place, as if you already have an ID that you wish to re-use for your Expense object table then it might just be a case of not passing the HiddenFor property correctly in the first place. 您的GET方法似乎期望将reportId作为参数,您能否首先告诉我们这个ActionMethod的内容,就好像您已经有一个ID,您希望为您的Expense对象表重用它然后它可能只是是一个没有正确传递HiddenFor属性的情况。

Unless the expenseID is set as an Identity Column in your database and mapping, you will have to set expenseID explicitly. 除非在数据库和映射中将expenseID设置为标识列,否则必须显式设置expenseID。

Something like this : 像这样的东西:

public ActionResult Create(int reportID)
{
    Expense ex = new Expense(){ 
        reportID = reportID,
        expenseID = **Some value** //Not advisable though

    };
    return View(ex);
}

However the preferred method would be to make your expenseId Column as Identity column and make it automatically incremented, like this : 但是,首选方法是将您的expenseId列作为标识列并使其自动递增,如下所示:

public class Expense
{
     [Key]
     public int expenseID {get;set;}
     public string expenseName {get;set;}
     public int reportID {get;set;}
}

将[HttpPost]属性添加到第二个ActionMethod.And参数必须是“Expense model”

My hidden field is inside form. 我隐藏的领域是内部形式。

Model: 模型:

public class Operations
{        
    public decimal firstValue { get; set; }        
}

First Action Method: 第一行动方法:

[HttpGet]
public ActionResult Index()
{
    Operations model = new Operations();
    model.firstValue = 100M;
    return View(model);
}

View: 视图:

@Html.HiddenFor(m => m.firstValue)
@Html.ActionLink("MyLink", "SampleGet", Model)//(for redirection)

Target Action Method: 目标行动方法:

[HttpGet]
public ActionResult SampleGet(Operations model)
{
    decimal myValue = model.firstValue;
    return View(model);
}

You can solve this in 2 ways. 您可以通过两种方式解决此问题。

1. From create method you not sending any expenseID to the view through model. 1.从create方法中,您不通过模型向视图发送任何expenseID。 You have to initilize ex.expenseID in action method Create. 您必须在操作方法Create中初始化ex.expenseID。

   public ActionResult Create(int reportID, int expenseID )
    {
        Expense ex = new Expense(){ 
            reportID = reportID,
            expenseID = expenseID /** Or expenseID = max(expenseID) +1 from expense table in database*/  
        };
        return View(ex);
    }

2. Or in post back create method 2.或者在post back create方法中

public ActionResult Create(Expense ex)
{
    if(ModelState.IsValid)
    {
        ex.expenseID = db.Expenses.Max( x => x.expenseID) + 1 ; 
        db.Expenses.Add(ex);
        db.SaveChanges();
        return RedirectToAction("Index");
   }
   return View(ex);

You will have to either pass the expenseID property value while creating new record. 您必须在创建新记录时传递expenseID属性值。 Else u can make expenseid as identity column by including this in your Context Class. 否则,您可以将expenseid作为标识列,将其包含在Context类中。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {           

            modelBuilder.Entity<Models.Expense>().HasKey(a => a.expenseID);
            modelBuilder.Entity<Models.Expense>().Property(a => a.expenseID).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);

            base.OnModelCreating(modelBuilder);
        }

You must explicitly initialised your expenseID . 您必须明确初始化您的expenseID

Yes, I know, we can expect that int will be initialised with 0 - but in my case it's not working when you passing object controller -> view (with hidden) -> controller . 是的,我知道,我们可以期望int将初始化为0 - 但在我的情况下,当你传递对象controller -> view (with hidden) -> controller时,它不起作用。 I'm not sure why. 我不知道为什么。

Try something like that: 尝试类似的东西:

public ActionResult Create(int reportID)
{
    Expense ex = new Expense(){ 
        expenseID = 0,
        reportID = reportID,
    };
    return View(ex);
}


I suppose that expenseID is your Primary Key in Db, so EF will compute proper Id when you set expenseID = 0 . 我认为expenseID是Db中的主键,因此当您设置expenseID = 0时,EF将计算正确的Id

If expenseID is your key, you should modify your code with these two line before 如果expenseID是您的密钥,您应该使用这两行修改您的代码

[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public int expenseID {get;set;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM