ASP.Net How can I access the correct item in the list

I am still a beginner in the ASP.Net world. My question is I think pretty easy to answer.

I have a list of products that are displayed with a foreach in the view:

@using (Html.BeginForm("Edit", "Products")){
<table class="table">
    <thead class="thead-dark">
            <th scope="col">Id</th>
            <th scope="col">Info</th>
            <th scope="col">Count</th>
        @foreach (var product in Model.ProductsList)
                <th scope="row">@Html.HiddenFor(x => product.Id)</th>
                <td>@Html.TextBoxFor(x => product.Info) </td>
                <td>@Html.TextBoxFor(x => product.Count) </td>
<button type="submit" class="btn btn-primary">Save</button>}

If I now try to get to the right element with this method, for example: There are 10 elements in the list and I click on the 5 element and change the info. If I now click on Save I should get back the 5 element I have edited in my method.

    public ActionResult Edit(Product product)
        if (product == null)
            return HttpNotFound();

        using (var _context = new Models.Database_.WebContext())
            var result = _context.Products.SingleOrDefault(x => x.Id == product.Id);
        return RedirectToAction("Index");

I think what I am missing is that I have to give the ID ?! The error is that my ID is always 0.

1 answer

  • answered 2020-06-02 09:42 suomi-dev

    You dont necessarily have to pass an Id since you are passing the whole model from your view. Your model is not being binded to your ActionResult parameter Product. Therefore, you get null object.

    Change your code to this:

    <th scope="row">@Html.Hidden("Id", product.Id)</th>
    <td>@Html.TextBox("Info", product.Info) </td>
    <td>@Html.TextBox("Count", product.Count) </td>

    As I remember,the "name" attribute is used for mapping. So after above changes, if you inspect (F12 on browser) your HTML you will see "name" attribute will be appended to your HTML elements.

    Also I notice a problem that your ActionResult accepts Product object but in your view you are submitting the list of products. Not sure why you doing so.