-1

sry for my bad english

I want to create list of data something like below:

<div>
  <input type="text" name="Users[0][FirstName]">
  <input type="text" name="Users[0][LastName]">
</div>
<div>
  <input type="text" name="Users[1][FirstName]">
  <input type="text" name="Users[1][LastName]">
</div>
.
.
.

But the inputs will create dynamically and when admin pushes the delete button of a div the index of Users (Users[index][FirstName]) will be disordered. Because of this I set a counter that never decreases but the problem is when I post Data sometimes it will be like this:

<div>
  <input type="text" name="Users[0][FirstName]">
  <input type="text" name="Users[0][LastName]">
</div>
<div>
  <input type="text" name="Users[2][FirstName]">
  <input type="text" name="Users[2][LastName]">
</div>

and in server side C# (list) gets data until the last index that exist and other index after that will be null. I have seen this scenario in opencart website for attributes in products and it has counter like me and send the data like my code but its handle the list. Is this a problem of model binder? How I can fix that?

SurvivalMachine
  • 7,946
  • 15
  • 57
  • 87
  • Refer [Submit same Partial View called multiple times data to controller?](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) –  Oct 06 '16 at 11:14

2 Answers2

0

This is not exactly a problem with the model binder. If you try to get the length of your array in JavaScript that too will count to the first null index. Bind a function to your form submit event, and iterate through your form inputs, create a clean javascript array which you post with Ajax. I'm assuming you've kept a counter when you dynamically add rows to the form.

$(document).ready(function(){
$('#myForm').on('submit', function(e){

});

});

Ali Kareem Raja
  • 566
  • 1
  • 7
  • 21
0

The code should be like

Index.cshtml

@using (@Html.BeginForm("Index", "Stackoverflow", FormMethod.Post))
{
    <div>
        <input type="text" name="users[0].FirstName">
        <input type="text" name="users[0].LastName">
    </div>
    <div>
        <input type="text" name="users[1].FirstName">
        <input type="text" name="users[1].LastName">
    </div>
    <input type="submit" value="submit"/>
}

and Controller

public class Users
    {
       public String FirstName { get; set; }
       public String LastName { get; set; } 
    }
    public class StackoverflowController : Controller
    {
        // GET: Stackoverflow
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(List<Users> users)
        {
            return null;
        }

    }

Put a break point in post method and see for your self

Syed Mhamudul Hasan
  • 1,341
  • 2
  • 17
  • 45