ASP.NET Core : send Id from view to controller

498 Views Asked by At

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?

1

There are 1 best solutions below

2
Qiang Fu On

I think you can try the mvc efcore sample first.
Step1. Create a mvc project.
Step2. Add a class ,such as "Category"

    public class Category
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string DisplayOrder { get; set; }
    }

Step3. right-click the "Controllers" folder, choose Add- Controller, then choose " MVC controller with views, using Entity Frameworkcore" enter image description here
Step4. Add as below (just press "+" to add dbcontext name.) enter image description here
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.

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

This makes the URL like Category/Edit/5 work 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")

        // GET: Categories/Edit/5
        public async Task<IActionResult> Edit(Guid? id)
        {
            if (id == null || _context.Category == null)
            {
                return NotFound();
            }

            var category = await _context.Category.FindAsync(id);
            if (category == null)
            {
                return NotFound();
            }
            return View(category);
        }

When you go to Category/Edit/5, it will use "5" to find the whole model and return it to page by return View(category). Thus, the id will inherit to be posted when you submit.