I need the Id from the model to be passed to the object in the get request.
View
@model Category
<form method="post">
<input type="hidden" asp-for="Id" value="@obj.Id"/>
<div class="border p-3 mt-4">
<div class="row pb-2">
<h2 class="text-primary">Create Category</h2>
</div>
<div class="mb-3">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control"/>
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="DisplayOrder"></label>
<input asp-for="DisplayOrder" class="form-control"/>
<span asp-validation-for="DisplayOrder" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary" style="width:150px">Create</button>
<a asp-controller="Category" asp-action="Index" class="btn btn-secondary" style="width:150px">
Back to List
</a>
</div>
</form>
@section Scripts {
@{
<partial name="_ValidationScriptsPartial" />
}
}
Controller
public IActionResult Edit(Category obj)
{
if (obj.Name == obj.DisplayOrder.ToString())
{
ModelState.AddModelError("name", "Имя не должно быть равным циферке внизу");
}
if (ModelState.IsValid)
{
_db.Categories.Update(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
Unfortunately, when an object enters the controller, its guid is all zeroes. I don't know what you can do about it. Maybe I need to use a hidden field, but that didn't work for me. Or send the object in a different way?
I think you can try the mvc efcore sample first.
Step1. Create a mvc project.
Step2. Add a class ,such as "Category"
Step3. right-click the "Controllers" folder, choose Add- Controller, then choose " MVC controller with views, using Entity Frameworkcore"

Step4. Add as below (just press "+" to add dbcontext name.)
Step4. This will generate a CRUD controller and views. Now change the database connectstring to yours and update it. (
add-migration initial,update-datebase).Now you can run this sample to see how it works.
In program.cs, there is a route map.
This makes the URL like
Category/Edit/5work and also bind the "5" with id parameter. You can check the controller Edit action method "get" (To clearify, your question method is for "post")When you go to
Category/Edit/5, it will use "5" to find the whole model and return it to page byreturn View(category). Thus, the id will inherit to be posted when you submit.