[SOLVED] ASP.NET MVC/JavaScript only 1 of added inputs is inserted into db

Issue

I have a JS that adds inputs to a option-container div.

When I submit the form, only 1 of the options is added to the database, and the ID in the database also shows as 0. This is what I have:

index.cshtml

@model AoTWiki.Models.DB.PollModel
...
<div class="form-group row">
    <h4 class="col-4 col-form-label text-light">Options <button id="addNewOptionBtn" class="btn btn-primary">+</button></h4>
    <div class="col-8">
        <div class="option-container">
        </div>
    </div>
    </div>
    <hr />
    <div class="form-group row">
        <div class="col-8 offset-4">
            <div class="row">
                <div class="col">
                    <a asp-action="index" asp-controller="home" class="btn btn-warning text-white form-control">Cancel</a>
                </div>
                <div class="col">
                    <button type="submit" class="btn btn-success form-control">Create Poll</button>
                </div>
           </div>
     </div>
</div>

@section Scripts
{
    <script>
        $("document").ready(function() {
            $("#addNewOptionBtn").click(function(e) {
                e.preventDefault();

                var count = $(".options").length;

                var newOption = "<input name='PollOptions["+count+"].OptionId' value='"+count+"' /><input name='PollOptions["+count+"].Option' placeholder='Option' /><br/><br/>";
                $(newOption).appendTo(".option-container");
            })
        });
    </script>

    <partial name="_ValidationScriptsPartial" />
}

PollController.cs

[HttpPost]
public ActionResult add(PollModel poll)
{
    if (ModelState.IsValid)
    {
        if (poll != null)
        {
            _mongo.ConnectToMongo<PollModel>("polls").InsertOne(poll);
        }
    }

    return RedirectToAction("index", "home");
}

PollModel.cs

[BsonId]
public ObjectId Id { get; set; }
public int PollId { get; set; }
public string? PollTitle { get; set; }
public IEnumerable<PollOptionModel>? PollOptions { get; set; }
public DateTime? CreatedAt { get; set; }
public bool IsActive { get; set; }

PollOptionModel.cs

[BsonId]
public ObjectId Id { get; set; }
public int OptionId { get; set; }
public string? Option { get; set; }

This is what the database looks like:

DB

EDIT:

This is what debugging shows. I made 3 options and then I pressed submit.
DEBUG

Also it’s worth mentioning that even the Id value in the input is also 0, I.E this, while it should increment as per the JS, if I’m not mistaken:
Empty Inputs

Solution

Looks like we forgot to wrap our input fields with a div with class="options". Hence only 0 is being returned by var count = $(".options").length;.

See the updated script below, var new option = "<div class='options'><input..."

<script>
   $("document").ready(function() {
      $("#addNewOptionBtn").click(function(e) {
         e.preventDefault();

         var count = $(".options").length;

         var newOption = "<div class='options'><input name='PollOptions["+count+"].OptionId' value='"+count+"' /><input name='PollOptions["+count+"].Option' placeholder='Option' /><br/><br/></div>";
         
         $(newOption).appendTo(".option-container");
      })
   });
</script>

Answered By – Jerdine Sabio

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *