Home > Enterprise >  ASP.NET MVC/JavaScript Add form element with JS & link element to model
ASP.NET MVC/JavaScript Add form element with JS & link element to model

Time:02-20

I'm trying to make a page where you'd press a button, 'Add Option', and it'd add another <input asp-for> to the form during runtime, which would then append the newly added <input asp-for>'s value to the Model's IEnumerable<PollOption>.

What's the best way to do it with JavaScript, if it's possible?

Here's what I have:

index.cshtml

<form method="post">
    <div id="optionsContainer" >
        <div >
            <div >
                Poll Title
            </div>
            <div >
                <input asp-for="PollTitle"  />
            </div>
        </div>
        <br />
        <div >
            <button id="addNewOptionBtn" >Add New Option</button>
            <div >
                Options:
            </div>
        </div>
    </div>
    <button type="submit" >Create Poll</button>
</form>

PollModel

[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

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

Any help is appreciated.

CodePudding user response:

Add a div with class name option-container.

<form method="post">
    ...
    <div >
       <button id="addNewOptionBtn" >Add New Option</button>
       <div >
          Options:
          <div >
          </div>
       </div>
    </div>
    ...
</form>

Then add this script (jquery is included by default in .net mvc), this will add a click event to your button which will add input fields.

@section scripts {
   <script>
      $(document).ready(function(){

         // click event
         $("#addNewOptionBtn").click(function(e){
            e.preventDefault();

            // this will be used as the index of the Ienumerable
            var count = $(".options").length;

            // new input fields to be inserted
            var newOption = "<input name='PollOptions[" count "].OptionId' placeholder='Option ID' value='" count "' /><input name='PollOptions[" count "].Option' placeholder='Option' /><br/><br/>";

            // insert the new input fields
            $(newOption).appendTo(".option-container");
         })
      });
   </script>
}

Hit submit in your form, add a break point on your code and check to see if the new poll options are bound to the model.

  • Related