最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to dynamically add row to html table - Stack Overflow

programmeradmin4浏览0评论

I got a ASP MVC 4.0 web application which enable user to dynamically add rows to html table.

In my view:

$('.del').live('click', function () {
    id--;

    var rowCount = $('#options-table tr').length;

    if (rowCount > 2) {
         $(this).parent().parent().remove();
    }  
});

$('.add').live('click', function () {
    id++;
    var master = $(this).parents("table.dynatable");

    // Get a new row based on the prototype row
    var prot = master.find(".prototype").clone();
    prot.attr("class", "")
    prot.find(".id").attr("value", id);

    master.find("tbody").append(prot);
});

<table class="dynatable" id="options-table" width="100%" style="text-align:center" border="1">
    <tr class="prototype">
        <%:Html.EditorFor(m => Model.ChillerDetails)%> //referring to the template
    </tr>
    <thead>
</table>

In my template:

<%@ Control  Language="C#" Inherits="System.Web.Mvc.ViewUserControl<GMIS.Models.GMISEBModels.ChillerPlantDetails>" %>

<div id="ChillerPlantDetails">
    <td><%: Html.EditorFor(m => m.ChillerAge) %></td>
    <td><%: Html.EditorFor(m => m.ChillerBrand) %></td>
    <td><%: Html.EditorFor(m => m.ChillerCapacity) %></td>
    <td><%: Html.EditorFor(m => m.ChillerRefrigerant) %></td>
    <td>
        <a href="#" class="add"><img src="<%= Url.Content("~/Content/Images/add.png") %>"/>&nbsp;<a href="#" class="del"><img src="<%= Url.Content("~/Content/Images/remove.png") %>"/>
    </td>
</div>

In my Model:

public class AddHealthCheckFormModel
{
    public List<ChillerPlantDetails> ChillerDetails { get; set; }
}

public class ChillerPlantDetails
{
    //[Required(ErrorMessage = "Please enter Chiller Capacity.")]
    [Display(Name = "Chiller Capacity")]
    public string ChillerCapacity { get; set; }

    //[Required(ErrorMessage = "Please enter Age of Chiller.")]
    [Display(Name = "Age of Chiller")]
    public string ChillerAge { get; set; }

    //[Required(ErrorMessage = "Please enter Chiller Brand.")]
    [Display(Name = "Chiller Brand")]
    public string ChillerBrand { get; set; }

    //[Required(ErrorMessage = "Please enter Chiller Refrigerant.")]
    [Display(Name = "Chiller Refrigerant")]
    public string ChillerRefrigerant { get; set; }
}

Now the question es to how can I capture the data in the dynamically added rows into my controller and save into database?

I got a ASP MVC 4.0 web application which enable user to dynamically add rows to html table.

In my view:

$('.del').live('click', function () {
    id--;

    var rowCount = $('#options-table tr').length;

    if (rowCount > 2) {
         $(this).parent().parent().remove();
    }  
});

$('.add').live('click', function () {
    id++;
    var master = $(this).parents("table.dynatable");

    // Get a new row based on the prototype row
    var prot = master.find(".prototype").clone();
    prot.attr("class", "")
    prot.find(".id").attr("value", id);

    master.find("tbody").append(prot);
});

<table class="dynatable" id="options-table" width="100%" style="text-align:center" border="1">
    <tr class="prototype">
        <%:Html.EditorFor(m => Model.ChillerDetails)%> //referring to the template
    </tr>
    <thead>
</table>

In my template:

<%@ Control  Language="C#" Inherits="System.Web.Mvc.ViewUserControl<GMIS.Models.GMISEBModels.ChillerPlantDetails>" %>

<div id="ChillerPlantDetails">
    <td><%: Html.EditorFor(m => m.ChillerAge) %></td>
    <td><%: Html.EditorFor(m => m.ChillerBrand) %></td>
    <td><%: Html.EditorFor(m => m.ChillerCapacity) %></td>
    <td><%: Html.EditorFor(m => m.ChillerRefrigerant) %></td>
    <td>
        <a href="#" class="add"><img src="<%= Url.Content("~/Content/Images/add.png") %>"/>&nbsp;<a href="#" class="del"><img src="<%= Url.Content("~/Content/Images/remove.png") %>"/>
    </td>
</div>

In my Model:

public class AddHealthCheckFormModel
{
    public List<ChillerPlantDetails> ChillerDetails { get; set; }
}

public class ChillerPlantDetails
{
    //[Required(ErrorMessage = "Please enter Chiller Capacity.")]
    [Display(Name = "Chiller Capacity")]
    public string ChillerCapacity { get; set; }

    //[Required(ErrorMessage = "Please enter Age of Chiller.")]
    [Display(Name = "Age of Chiller")]
    public string ChillerAge { get; set; }

    //[Required(ErrorMessage = "Please enter Chiller Brand.")]
    [Display(Name = "Chiller Brand")]
    public string ChillerBrand { get; set; }

    //[Required(ErrorMessage = "Please enter Chiller Refrigerant.")]
    [Display(Name = "Chiller Refrigerant")]
    public string ChillerRefrigerant { get; set; }
}

Now the question es to how can I capture the data in the dynamically added rows into my controller and save into database?

Share Improve this question edited Nov 28, 2013 at 17:30 Charles 51.4k13 gold badges106 silver badges144 bronze badges asked Aug 24, 2013 at 6:34 vincentvincent 5172 gold badges6 silver badges12 bronze badges 1
  • you can save the rows by ajax call and also by doing postback, what you want through ajax or full postback? – Ehsan Sajjad Commented Aug 24, 2013 at 6:57
Add a ment  | 

1 Answer 1

Reset to default 4

You can use following View which will add new record using HTTP Post instead of Ajax. Replacing it with Ajax.BeginForm with appropriate parameters will use the Ajax instead of plain post request.

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<table class="list-chiller-record">
    @for (int i = 0; i < this.Model.ChillerDetails.Count; i++)
    {
        if (i == 0)
        {
            <tr class="chiller-record-template" style="display:none">
                <td>@Html.EditorFor(x=>x.ChillerDetails[i].ChillerAge)</td>
                <td>@Html.EditorFor(x=>x.ChillerDetails[i].ChillerBrand)</td>
                <td>@Html.EditorFor(x=>x.ChillerDetails[i].ChillerCapacity)</td>
                <td>@Html.EditorFor(x=>x.ChillerDetails[i].ChillerRefrigerant)</td>
            </tr>    
        }

        <tr class="chiller-record">
            <td>@Html.EditorFor(x=>x.ChillerDetails[i].ChillerAge)</td>
            <td>@Html.EditorFor(x=>x.ChillerDetails[i].ChillerBrand)</td>
            <td>@Html.EditorFor(x=>x.ChillerDetails[i].ChillerCapacity)</td>
            <td>@Html.EditorFor(x=>x.ChillerDetails[i].ChillerRefrigerant)</td>
        </tr>

    }
</table>
<br />
<input type="button" class="add-button" name="add" value="Add" />
<input type="submit" class="save-button" name="save" value="save" />
}

Add add new row:

  <script type="text/javascript">
    $(document).ready(function () {
        var count = 2;
        $('.add-button').click(function () {
            count++;
            var template = $('.chiller-record-template').clone()
            template.find('input[type=text]').val('');
            $.each(template.find('input[type=text]'), function () {
                var name = $(this).attr('name');
                name = name.replace('0', count - 1);
                $(this).attr('name', name);
            });

            $('.list-chiller-record').append(template);
            template.removeClass('chiller-record-template').addClass('chiller-record').show();
        })
    });
 </script>

Your Action Could be like this:

 [HttpPost]
    public ActionResult AddHealthCheck(AddHealthCheckFormModel model)
    {
        if (ModelState.IsValid)
        {
            HealthCheckRepository healthCheckRepository = new HealthCheckRepository();
            healthCheckRepository.save(model);
        }

        return this.View(model);
    }

And in repository you can actually save the data in database. You can use EF or any other ORM for this.

发布评论

评论列表(0)

  1. 暂无评论