我想在Ajax调用后呈现局部视图

时间:2013-01-11 17:19:51

标签: jquery asp.net-mvc

我从AJAX调用返回一个局部视图,但它没有被渲染。看起来没有调用showOtherTrade函数,请参阅下面的代码;

我的观点是;

@model SCD.ViewModels.OtherTradesViewModel

@{
    ViewBag.Title = "Edit Other Trades";
}
<fieldset>
    <legend>Edit Other Trades for the subcontractor @Model.Subcontractor.CompanyName</legend>
    <p class="highlight">@ViewBag.Message</p>
    <p>The Primary Trade is set to @Model.PrimaryTradeName</p>

    <form method="get" action="@Url.Action("EditOtherTrades")" 
          data-scd-ajax="true" data-scd-target="#otherTradeList">
        <p>Select a trade: <input type="search" name="searchOtherTrade" id="searchOtherTrade" data-scd-autocomplete="@Url.Action("AutocompleteOtherTrade", "DataService")" style = "width: 300px;" class="submitSelection"/>
        </p>
    </form>  

    @Html.Partial("_OtherTrades", Model.OtherTrades.ToList())
</fieldset>

我的PartialView是 @model IList

<div id="otherTradeList">
    <table>
        @Html.DisplayForModel()
    </table>
</div>

DisplayTemplate是;

@model SubcontractorTrade
<tr>
    <td>@Model.Trade.TradeName </td>
    <td><input type="button" value="Remove"/>@Html.HiddenFor(model => model.TradeId)</td>
</tr>

我正在使用自动填充功能连接到要添加到网格的数据项目。

所以我的javascript看起来像;

var showOtherTrade = function (data) {
        var $form = $(this);
        var $target = $($form.attr("data-scd-target"));
        var $newHtml = $(data);
        $target.replaceWith($newHtml);
        $newHtml.effect("highlight");
    };

    var updateAutocompleteForm = function (event, ui) {
        var $input = $(this);

        if ($input.hasClass("submitSelection")) {
            $input.val("");
            var searchId = ui.item.id;
            url = AddOtherTradeUrl;
            dataService.addOtherTrade(searchId, showOtherTrade, url);
        } 
    };

    var createAutocomplete = function () {
        var $input = $(this);

        var options = {
            source: $input.attr("data-scd-autocomplete"),
            select: updateAutocompleteForm
        };

        $input.autocomplete(options);
    };

似乎没有调用showOtherTrade函数。这可能是我需要解决的问题。

我的数据服务,如果你有兴趣,看起来像;

var dataService = new function () {
    $.ajaxSetup({
        cache: false
    });
    addOtherTrade = function(searchId, callback, url) {
        $.getJSON(url,
            { searchId: searchId },
            function(data) {
                callback(data);
            });
        };

        return {
            addOtherTrade: addOtherTrade
        };
} ();

1 个答案:

答案 0 :(得分:4)

您可以成功或失败调用此代码ajax调用

$.get(action, null, function(data){
  $('#someDiv').html(data);
}, 'html');

并且您的控制器可以返回:

return PartialView("SomePartial", Model)