0

I want to dynamically add textboxes and bind it to my model, so when I post all data should be in HttpPost. Here is my model

 public class JobViewModel
    {
        public JobViewModel()
        {
            JobDescriptions = new List<JobDescription>();
        }
        public int Id { get; set; }
        [Required]
        public string JobTitle { get; set; }
        public List<JobDescription> JobDescriptions { get; set; }
}

Here is my Razor view

@using (Html.BeginForm("CreateJob", "Jobs", FormMethod.Post, new { @id = "jobFrm" }))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
    <h4>Job</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.JobTitle, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.JobTitle, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.JobTitle, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.Label("Add Description", htmlAttributes: new { @class = "control-label col-md-2" })
       


 <div class="col-md-2">
            <input id="btnAdd" type="button" class="btn btn-success" value="Add"  />
        </div>

 ............. more fields and submit button ............

I searched and tried different codes, they add textboxes while clicking ADD button, but that filled textboxes value are not binded to my model. Sometimes it add empty model, or none at all. Need help to bind values to my model

2 Answers2

0

You can choose one of two solutions as per need:

  • If you are add dynamic control from Razor at time of rendering then use conditional add of control.
  • If you want to do this at run time, therefore in browser through javascript then use proper name and id fields to create and map back.
Imran Javed
  • 11,779
  • 2
  • 16
  • 17
0

I referenced this when trying to create a form with dynamic add/delete functionality for a one to many relationship. One major thing to keep in mind is to ensure the index of the newly added item. Also as stated above, there will be some client side calls to add a new editor for each specific item. This post also provided me with some great reference when setting up my editor templates with the client side call to "AddNewItem" to the form and ensuring that the index of the newly added item was available for deleting if necessary.

Eric
  • 505
  • 5
  • 22