Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

109
Vistas
ASP.NET MVC/JavaScript Add form element with JS & link element to model

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" class="col-8 pt-4">
        <div class="form-group row">
            <div class="col-6 text-center text-light">
                Poll Title
            </div>
            <div class="col-6">
                <input asp-for="PollTitle" class="form-control" />
            </div>
        </div>
        <br />
        <div class="form-group row">
            <button id="addNewOptionBtn" class="btn btn-primary">Add New Option</button>
            <div class="col-6 text-center text-light">
                Options:
            </div>
        </div>
    </div>
    <button type="submit" class="btn btn-success form-control">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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Add a div with class name option-container.

<form method="post">
    ...
    <div class="form-group row">
       <button id="addNewOptionBtn" class="btn btn-primary">Add New Option</button>
       <div class="col-6 text-center text-light">
          Options:
          <div class="option-container">
          </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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda