在部分视图上执行脚本

时间:2014-09-22 17:57:33

标签: javascript ajax asp.net-mvc

我在主视图中有以下脚本,可以很好地创建级联下拉列表。但是,我无法在部分视图加载后执行它。从我在网上看到的,似乎我需要在局部视图中进行某种类型的Ajax调用(我对如何编写完全无能为力)。任何援助将不胜感激。

<script type="text/javascript">
    $(function () {
        $("#SelectedCollateralClass").change(function () {
            var selectedItem = $(this).val();
            var ddlTypes = $("#SelectedCollateralType");
            var typesProgress = $("#types-loading-progress");
            typesProgress.show();
            $.ajax({
                cache: false,
                type: "GET",
                url: "@(Url.RouteUrl("GetCollateralTypesByClass"))",
                data: { "CollateralClassId": selectedItem },
                success: function (data) {
                    ddlTypes.html('');
                    $.each(data, function (id, option) {
                        ddlTypes.append($('<option></option>').val(option.id).html(option.name));
                    });
                    typesProgress.hide();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve types.');
                    typesProgress.hide();
                }
            });
        });
    });
</script>

我的主要观点是:

@model CollateralRowViewModel

<div class="APPLICATION">

    @*@Html.Partial("_SideBarView.cshtml");
    @Html.Partial("_CommentsView.cshtml");*@

    <!-- Content ======================================================================================-->

    <div class="container row">
        @using (@Html.BeginForm())
        {
            <div class="col-xs-16">
                <div class="hr">
                    <h3 class="inline-block"> Collateral</h3>
                    <a class="icon-add"></a>
                </div>
                <table class="dataentry">
                    <thead>
                        <tr>
                            <th>@Html.LabelFor(model => model.CollateralClass)</th>
                            <th>@Html.LabelFor(model => model.CollateralType)</th>
                            <th>@Html.LabelFor(model => model.Description)</th>
                            <th>@Html.LabelFor(model => model.MarketValue)</th>
                            <th>@Html.LabelFor(model => model.PriorLiens)</th>
                            <th>@Html.LabelFor(model => model.AdvanceRate)</th>
                            <th>@Html.Label("Grantor (if not Borrower)")</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                <span class="inputROW">
                                    @Html.DropDownListFor(model => model.SelectedCollateralClass, Model.CollateralClass)
                                </span>
                            </td>
                            <td>
                                <span class="inputROW">
                                    @Html.DropDownListFor(model=>model.SelectedCollateralType, Model.CollateralType)
                                </span>
                            </td>
                            <td>
                                <span class="inputROW">
                                    @Html.TextBoxFor(model => model.Description)
                                </span>
                            </td>
                            <td>
                                <span class="inputROW">
                                    @Html.TextBoxFor(model => model.MarketValue)
                                </span>
                            </td>
                            <td>
                                <span class="inputROW">
                                    @Html.TextBoxFor(model => model.PriorLiens)
                                </span>
                            </td>
                            <td>
                                <span class="inputROW">
                                    @Html.TextBoxFor(model => model.AdvanceRate)
                                </span>
                            </td>
                            <td>
                                <span class="inputROW Smargin_bottom">
                                    @Html.TextBoxFor(model => model.GrantorFirstName)
                                </span>
                                <span class="inputROW">
                                    @Html.TextBoxFor(model => model.GrantorMiddleName)
                                </span>
                                <span class="inputROW">
                                    @Html.TextBoxFor(model => model.GrantorLastName)
                                </span>
                            </td>
                            <td class="minusRow">
                                <a class="btn btn-danger icon-subtract sm btn-xs" data-nodrag ng-click="remove(this)"></a>
                            </td>
                        </tr>

                    </tbody>

                </table>
                <div>
                    <input id="addBtn" type="button" value="Add New Collateral" />
                </div>
            </div>
        }
    </div> <!-- end container -->


    <footer id="APPfooter">
        <div class="pagination centerF">
            <ul>
                <li class="previous"><a href="#" class="icon-arrow-01"></a></li>
                <li class="next"><a href="#" class="icon-arrow-01"></a></li>
            </ul>
        </div>
    </footer>

</div><!-- end page content container-->


<script type="text/javascript" charset="utf-8">
        $(function () {
            $('.default').dropkick();
            $( "#datepicker" ).datepicker();
        });
</script>
<script>
    $("#addBtn").on("click", function () {

        $.get('@Url.Action("AddNewRow")', function (data) {
            $("table").append(data);
        });

    });
</script>

<script type="text/javascript">
    $(document).ready(
    $(function () {
        $("#SelectedCollateralClass").change(function () {
            var selectedItem = $(this).val();
            var ddlTypes = $("#SelectedCollateralType");
            var typesProgress = $("#types-loading-progress");
            typesProgress.show();
            $.ajax({
                cache: false,
                type: "GET",
                url: "@(Url.RouteUrl("GetCollateralTypesByClass"))",
                data: { "CollateralClassId": selectedItem },
                success: function (data) {
                    ddlTypes.html('');
                    $.each(data, function (id, option) {
                        ddlTypes.append($('<option></option>').val(option.id).html(option.name));
                    });
                    typesProgress.hide();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve types.');
                    typesProgress.hide();
                }
            });
        });
    }));
</script>

我的部分看起来像:

@model CollateralRowViewModel

                <tr>
                    <td>
                        <span class="inputROW">
                            @Html.DropDownListFor(model=>model.SelectedCollateralClass, Model.CollateralClass)
                        </span>
                    </td>
                    <td>
                        <span class="inputROW">
                           @Html.DropDownListFor(model=>model.SelectedCollateralType, Model.CollateralType)
                        </span>
                    </td>
                    <td>
                        <span class="inputROW">
                            @Html.TextBoxFor(model=>model.Description)
                        </span>
                    </td>
                    <td>
                        <span class="inputROW">
                            @Html.TextBoxFor(model=>model.MarketValue)
                        </span>
                    </td>
                    <td>
                        <span class="inputROW">
                            @Html.TextBoxFor(model=>model.PriorLiens)
                        </span>
                    </td>
                    <td>
                        <span class="inputROW">
                            @Html.TextBoxFor(model=>model.AdvanceRate)
                        </span>
                    </td>
                    <td>
                        <span class="inputROW Smargin_bottom">
                            @Html.TextBoxFor(model=>model.GrantorFirstName)
                        </span>
                        <span class="inputROW">
                            @Html.TextBoxFor(model=>model.GrantorMiddleName)
                        </span>
                        <span class="inputROW">
                            @Html.TextBoxFor(model=>model.GrantorLastName)
                        </span>
                    </td>
                    <td class="minusRow">
                        <a class="btn btn-danger icon-subtract sm btn-xs" data-nodrag ng-click="remove(this)"></a>
                    </td>
                </tr>

Controller Action是:

 [AcceptVerbs(HttpVerbs.Get)]
    public async Task<ActionResult> GetCollateralTypesByClass(Guid collateralClassId)
    {
        var collateralServiceProxy = base.ServiceProvider.CollateralServiceProxy;
        var collateralTypes = await collateralServiceProxy.GetCollateralTypesByCollateralClassIdAsync(collateralClassId);

        var selectCollateraltypes = (from t in collateralTypes
                                     select new
                                     {
                                         id = t.Id.ToString(),
                                         name = t.Name
                                     }).ToList();

        return Json(selectCollateraltypes, JsonRequestBehavior.AllowGet);
    }

通过按钮调用Partial&#34; Add New&#34;如下:

<script>
    $("#addBtn").on("click", function () {

        $.get('@Url.Action("AddNewRow")', function (data) {
            $("table").append(data);
        });

    });
</script>

按钮的控制器是:

[HttpGet]
[Route("CreateRow")]
public async Task<ActionResult> AddNewRow()
{
    var collateralClasses = await GetCollateralClasses();
    var collateralTypes = await GetCollateralTypes();

    var model = new CollateralRowViewModel();

    model.CollateralClass.Add(new SelectListItem { Text = "-Please Select-", Value = "-1" });
    foreach (var _class in collateralClasses)
    {
        model.CollateralClass.Add(new SelectListItem()
        {
            Value = _class.Value.ToString(),
            Text = _class.Text.ToString()
        });
    }

    model.CollateralType.Add(new SelectListItem { Text = "-Please Select-", Value = "-1" });
    foreach (var type in collateralTypes)
    {
        model.CollateralType.Add(new SelectListItem()
        {
            Value = type.Value.ToString(),
            Text = type.Text.ToString()
        });
    }
    return PartialView("_newCollateralRow", model);
}

1 个答案:

答案 0 :(得分:0)

我得到了答案。我需要做的就是在Partial中添加新的{@class =&#34; ddlClass&#39;}和新的{@class =&#34; ddlType&#34;}。然后我只是将脚本复制到Partial,并将引用从引用Id更改为引用新类,如下所示:

<script type="text/javascript">

    $(function () {
        $(".ddlClass").change(function () {
            var selectedItem = $(this).val();
            var ddlTypes = $(".ddlType");
            var typesProgress = $("#types-loading-progress");
            typesProgress.show();
            $.ajax({
                cache: false,
                type: "GET",
                url: "@(Url.RouteUrl("GetCollateralTypesByClass"))",
                data: { "CollateralClassId": selectedItem },
                success: function (data) {
                    ddlTypes.html('');
                    $.each(data, function (id, option) {
                        ddlTypes.append($('<option></option>').val(option.id).html(option.name));
                    });
                    typesProgress.hide();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve types.');
                    typesProgress.hide();
                }
            });
        });
    });
</script>

我希望这有助于其他人!