C#C
C#2y ago
yatta

The value '' is invalid. for primary key in MVC

I'm practicing MVC with asp.net and building a simple todo app. I have my Model:
    public class Todo
    {
        public int Id { get; set; }
 
        public string? Name { get; set; }
    }
}

and MVC controller:
        public IActionResult Insert()
        {
            return View("_Form");
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Insert([Bind("Id, Name")]Todo todo)
        {
            if (ModelState.IsValid)
            {
                _context.Add(todo);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View("_Form",todo);
        }

and my view _Form.cshtml:
@model Todo
<form asp-action="Insert" id="form-action" method="post" role="form">
    <div asp-validation-summary="All"></div>
    <label asp-for="Name"></label>
    <input asp-for="Id" type="hidden" />
    <input asp-for="Name" />
    <span asp-validation-for="Name"></span>
    <input type="submit" id ="form-button" value="Add Todo" />
</form>

When I try to run the program, the data is not written into my database and I also get the error The value '' is invalid , when I run the program in debug, the error cause from Id value, from what I found on the internet, people that had this error only cause with other attribute, but not primary key as mine. So I'm frustrated right now, because it's primary key, so I cannot just make it nullable or assign a default value as the normal attribute.
image.png
Was this page helpful?