0

In a page I show a list of books, and there is a button "Add New Book", I want an item added to list if user clicked, it works.

but if user click on "Submit" button, in a controller 2 books just posted that I created in code

enter image description here

View:

@model WebApplication2.Models.Book2

@{
    ViewBag.Title = "Index";
}


@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10 text-right">
            <input type="button" onclick="@Url.Action("PlaceOrder")" value="Add Product" class="btn btn-primary" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-12">
            <table class="table table-condensed table-hover">
                <tbody id="books">
                    <tr>
                        <th>
                            Product Code
                        </th>
                        <th>
                            Product Name
                        </th>
                    </tr>
                    @{
                        int i = 0;
                        foreach (var item in Model.Books.ToList())
                        {

                    <tr>
                        <td>
                            @Html.EditorFor(o => o.Books[i].Author, new { @id = "Author_" + i })
                        </td>
                        <td>
                            @Html.EditorFor(o => o.Books[i].Title, new { @id = "Title_" + i })
                        </td>

                        <td>
                            @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                            @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                            @Html.ActionLink("Delete", "Delete", new { id = item.ID })
                        </td>
                    </tr>
                            i++;
                        }
                    }
                </tbody>
            </table>
        </div>
    </div>
    <hr />
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10 text-center">
            <input type="button" id="addbook2" name="addbook" value="Add New Book" />
            <input type="submit" value="Submit" class="btn btn-primary" />
        </div>
    </div>
</div>

@section Scripts {
    <script type="text/javascript">

        $("#addbook2").on('click', function () {

            $.ajax({
                async: false,
                url: '/Book/CreateNewBook',
                success: function (partialView) {
                    console.log("success");
                    $('#books').append(partialView);
                }
            })
        });

    </script>
}
} 

controller code:

public class BookController : Controller
{
    public ActionResult Index()
    {
        Book[] books = new Book[]
        {
            new Book()
            {
                ID = 1, Title = "title01", Author = "author01",
            },
            new Book()
            {
                ID = 2, Title = "title02", Author = "author02",
            },
        };
        return View(new BooksContainer()
        {
            Books = books.ToList(),
        });
    }

    [HttpPost]
    public ActionResult Index(BooksContainer books)
    {
        // books.Books.Count is 2! why?
        return View();
    }

    public ActionResult CreateNewBook()
    {
        var book = new Book()
        {
            ID = new Random().Next(3, 999_999),
        };

        return PartialView("~/Views/Shared/createBook.cshtml", book);
    }
}

CreateBook PartialView:

@model WebApplication2.Models.Book


<tr>
    <td>
        @Html.EditorFor(o => o.Author, new { @id = "Author_" + Model.ID })
    </td>
    <td>
        @Html.EditorFor(o => o.Title, new { @id = "Title_" + Model.ID })
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
        @Html.ActionLink("Details", "Details", new { id = Model.ID }) |
        @Html.ActionLink("Delete", "Delete", new { id = Model.ID })
    </td>
</tr>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

inspected elements: enter image description here

why count of books in post controller is 2 and I can not see added books.

if I set name of third <tr> inputs manually to Books[2].Author and Books[2].Title after submit, in a controller I can see 3 books. how fix this problem?

Mojtaba Khooryani
  • 1,763
  • 1
  • 17
  • 36
  • I think what you need is an editor template for your Book model and then using `EditorFor(o => o.Books[i])` in your foreach loop. – prinkpan Dec 28 '18 at 12:35
  • Possible duplicate of [Add item into List from View and pass to Controller in MVC5](https://stackoverflow.com/questions/39129555/add-item-into-list-from-view-and-pass-to-controller-in-mvc5) – VDWWD Dec 28 '18 at 13:14

1 Answers1

0

Names must be Books[1].Author,Books[2].Author,Books[3].Author to be interpreted as three element of a array. A possible workaround could be

public ActionResult CreateNewBook(BooksContainer books)
{
    var book = new Book()
    {
        ID = new Random().Next(3, 999_999),
    };
    books.Book.Add(book);


    return View(books);
}

Another way could be somehow store the array in the session and take the last book and add to the partial view like

 @Html.EditorFor(o => o.Books[indexofthelastbook].Author, new { @id "Author_" + Model.ID })

But doing these with javascript will be a far better option