Обновление HTML-таблицы с помощью jQuery для поддержки модальной привязки в ASP.NET MVC - PullRequest
0 голосов
/ 26 января 2010

Прямо сейчас пользователи нажимают кнопку с JQuery. Он динамически добавляет новую форму каждый раз. Мне нужен способ в JQuery или C #, который может обновить индекс, чтобы он имел следующий формат. HTML создается в пользовательском элементе управления в ASP.NET MVC. Я пытался использовать строку для индексов, но она не связывает модель правильно. Я прочитал следующий пост в блоге текст ссылки

// Jquery that handles user click event of the button
// Jquery that handles user click event of the button
// Jquery that handles user click event of the button

    $(".addDetail").click(function() {
    if ($("#rateFormContainer").css("display")!= "none") {
        $.ajax({
            url: "/Rates/NewRateDetail/",
            cache: false,
            success: function(html) {

                $("#rdContainer").append(html);
            }
        });
        $("#rateDetailMsg").empty()                
        }
    });

// The end result of the view, what I want to do
// The end result of the view, what I want to do
// The end result of the view, what I want to do
// Update the Index to 0 for this element
<input type="hidden" value="0" name="RateDetail.Index" id="RateDetail_Index">
<input type="text" value="" name="RateDetail[0].EffectiveDate" id="RateDetail[0]_EffectiveDate">

// Update the Index to 1 for this element
<input type="hidden" value="1" name="RateDetail.Index" id="RateDetail_Index">
<input type="text" value="" name="RateDetail[1].EffectiveDate" id="RateDetail[1]_EffectiveDate">

// Update the Index to 2 for this element
<input type="hidden" value="2" name="RateDetail.Index" id="RateDetail_Index">
<input type="text" value="" name="RateDetail[2].EffectiveDate" id="RateDetail[2]_EffectiveDate">

// Use JQuery to update all items to correct indexes on sumbmit
<input type="submit" class="prettyButton" value="Submit">


// ASP.NET MVC user control code
// ASP.NET MVC user control code
// ASP.NET MVC user control code
// ASP.NET MVC user control code

<%=Html.Hidden(Resources.RSINET.RateDetailIndex, "0")%>

<table class="prettyForm">
<thead>
    <th colspan="2">Add Rate Details</th>
</thead>
<tr>
    <td>Effective Date</td>
    <td><%=Html.TextBox(Resources.RSINET.RateDetailBrace + "0" + Resources.RSINET.BraceEffectiveDate)%>  <a href="javascript:NewCal('RateDetail[<%="0"%>].EffectiveDate','mmddyyyy')"><img src="../../Content/Images/cal.gif" width="16" height="16" border="0" alt="Pick a date"/></a></td>
</tr>
<tr>
    <td>Expiration Date</td>
    <td><%=Html.TextBox(Resources.RSINET.RateDetailBrace + "0" + Resources.RSINET.BraceExpirationDate)%> <a href="javascript:NewCal('RateDetail[<%="0"%>].ExpirationDate','mmddyyyy')"><img src="../../Content/Images/cal.gif" width="16" height="16" border="0" alt="Pick a date"/></a></td>
</tr>
<tr>
    <td>Condition Type</td>
    <td><%=Html.DropDownList(Resources.RSINET.RateDetailBrace + "0" + Resources.RSINET.BraceConditionType, ViewData.Model.CondT, "Choose Option")%></td>
</tr>
<tr>
    <td>Condition Value</td><td><%=Html.TextBox(Resources.RSINET.RateDetailBrace + "0" + Resources.RSINET.BraceConditionValue)%></td>
</tr>
<tr>
    <td>Rate</td><td><%=Html.TextBox(Resources.RSINET.RateDetailBrace + "0" + Resources.RSINET.BraceRate)%> </td>
</tr>
<tr>
    <td>Unit</td><td><%=Html.DropDownList(Resources.RSINET.RateDetailBrace + "0" + Resources.RSINET.BraceUnit, ViewData.Model.Unit, "Choose Option")%></td>
</tr>
<tr>
    <td>Status</td>
    <td><%=Html.DropDownList(Resources.RSINET.RateDetailBrace + "0" + Resources.RSINET.BraceActiveItem, ViewData.Model.Active, "Choose Option")%></td>
</tr>


</table>

1 Ответ

1 голос
/ 26 января 2010

РЕДАКТИРОВАТЬ: Вот код JavaScript, я думаю, что вам нужно. Это предполагает, что "/ Rages / NewRateDetail" возвращает другую копию <table class="prettyForm">. Смотрите полный автономный пример (в простом HTML) ниже.

$(".addDetail").click(function() {
if ($("#rateFormContainer").css("display")!= "none") {
    $.ajax({
        url: "/Rates/NewRateDetail/",
        cache: false,
        success: function(html) {

            $("#rdContainer").append(html);

                $("#rdContainer table.prettyForm").each(function(i, el) {

                    $("input,select,textarea", el).each(function(j,formEl) {
                        $(formEl)
                            .attr("name", $(formEl).attr("name").replace(/\[\d\]/, "["+ i +"]"))
                            .attr("id", $(formEl).attr("id").replace(/\[\d\]/, "["+ i +"]"));
                    });
                });

        }
    });
    $("#rateDetailMsg").empty()                
    }
});

Вот код, который копирует всю таблицу prettyForm каждый раз, когда вы нажимаете кнопку «Добавить». Затем он просматривает каждую таблицу и обновляет атрибуты поля id и name, соответствующие текущему индексу цикла.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#add").click(function(e) {
                e.preventDefault();             

                $("table.prettyForm:first").clone().insertBefore(this);

                $("table.prettyForm").each(function(i, el) {

                    $("input,select,textarea", el).each(function(j,formEl) {
                        $(formEl)
                            .attr("name", $(formEl).attr("name").replace(/\[\d\]/, "["+ i +"]"))
                            .attr("id", $(formEl).attr("id").replace(/\[\d\]/, "["+ i +"]"));
                    });
                });

                return false;
            })
        });
    </script>
</head>

<body>
    <table class="prettyForm">
        <thead>
            <th colspan="2">
            Add Rate Details
            <input type="hidden" value="0" name="RateDetail.Index" id="RateDetail_Index">
            </th>
        </thead>
        <tr>
            <td>Effective Date</td>
            <td><input type="text" value="" name="RateDetail[0].EffectiveDate" id="RateDetail[0]_EffectiveDate"></td>
        </tr>
        <tr>
            <td>Expiration Date</td>
            <td><input type="text" value="" name="RateDetail[0].ExpirationDate" id="RateDetail[0]_ExpirationDate"></td>
        </tr>
        <tr>
            <td>Status</td>
            <td><select name="RateDetail[0].Status" id="RateDetail[0].Status"></select></td>
        </tr>
    </table>
    <button id="add">Add Form</button>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...