简体   繁体   中英

HttpPost Model ID is always 0

I have an Update page getting a ViewModel containing my Model. When I load it to the page everything works fine but when I submit the changes my Model's ID is ALWAYS 0, I mean LITTERALY ALWAYS . I am following a tutorial, I did exactly what he did and STILL 0.

This is my POST method where I'm passing the VM in parameter.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Update(ExpenseVM obj)
    {
        if (ModelState.IsValid)
        {
            _db.Expenses.Update(obj.Expense);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(obj);
    }

And here is my HTML/C# code for the ID

<input type="hidden" asp-for="Expense.Id" value="@Model.Expense.Id" name="Id"/>

When I load my page my ID is loaded and everything works fine. During debugging this is what I have in my HTML:

<input type="hidden" value="1" name="Id" data-val="true" data-val-required="The Id field is required." id="Expense_Id">

I found out why it didn't work.

My HTML was like this

<form method="post" asp-action="Update">
   <div class="border p-3">
      <div class="form-group row">
         <h2 class="text-black-50 pl-3">Update Expense</h2>
      </div>
      <div class="row">
         <input type="hidden" asp-for="Expense.Id" value="@Model.Expense.Id" name="Id"/>
         <div class="col-12">
            ... BLABLABLA
         </div>
      </div>
   </div>
</form>

So I just moved the input line from inside <div class="row> to <form method="post" asp-action"Update"> and removed all these useless tags like name="Id" value="@Model.Expense.Id" type="hidden"

And now it looks just like this

<form method="post" asp-action="Update">
   <input asp-for="Expense.Id" hidden/>
   <div class="border p-3">
      <div class="form-group row">
         <h2 class="text-black-50 pl-3">Update Expense</h2>
      </div>
      <div class="row">
         <div class="col-12">
            ... BLABLABLA
         </div>
      </div>
   </div>
</form>

And it works fine.

Now please DO NOT ask me why because I don't know, but if ANYONE has the answer to WHY ? I'm all ears.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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