0

I think I am missing something little.

All I want to do is to pass the List of models from View to Controller, I have 7 items and I succeeded to pass those 7 items but all its properties values are default.

This is my view:

@model List<News>

@using (Html.BeginForm("SaveNewsPositions", "home", new { area = "news" }, FormMethod.Post))
    {
        <a href="#" id="savePositions">Save positions</a>
        <div class="news-items">
            @foreach (var news in Model)
            {
                @Html.Partial("_NewsControl", news)
            }
        </div>
    }

And the JS code:

 $('#savePositions').on('click', function () {
    var form = $('form');
    $.post('@Url.Action("SaveNewsPositions", "home", new {area = "news"})', form.serialize(), function (response) {
        if (response.success) {
            //TODO...
        }
});

When I debug the form.serialize() I see the object with all values, for example:

Position=1&Id=106 etc...

But when it comes to the Controller:

[HttpPost]
public JsonResult SaveNewsPositions(List<News> models)
{
    //Some Code...
}

I see that models have 7 items and each item has Position with 0 value and Id that is identity (first item: id = 1, second id = 2, etc.).

How can I fix it?

Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116
  • Please note that the model-view-controller tag is for questions about the pattern. There is a specific tag for the ASP.NET-MVC implementation. –  Sep 11 '16 at 08:34
  • You cannot use a `foreach` and partial view to generate form controls for a collection (unless you pass the collection indexer as a `HtmlFieldPrefix` - refer [this answer](http://stackoverflow.com/questions/29808573/getting-the-values-from-a-nested-complex-object-that-is-passed-to-a-partial-view/29809907#29809907)). The correct way to generate you view is to use a `for` loop or custom `EditorTemplate` - refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) –  Sep 11 '16 at 08:38
  • And just realized, you were already advised of this in your [previous question](http://stackoverflow.com/questions/39194371/partial-view-list-returns-null-when-saving-the-model) –  Sep 11 '16 at 08:40

0 Answers0