在AJAX调用后返回不同的视图

时间:2018-07-26 03:16:03

标签: ajax asp.net-mvc post

我已将ajax添加到我的编辑页面。我不知道该如何解决这个问题:

[ValidateAntiForgeryToken]
[HttpPost]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.SystemEditValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValue)]
public IActionResult EditValue([FromBody] AureliaCMS.Models.ValueType valueType)
{
    if (ModelState.IsValid)
    {
        repository.SaveValueType(valueType);
        return View(RouteUrl.Save, new SaveCategoryType(repository.GetCategoryByTypeId(valueType.TypeId).IsSysParam, valueType.Value, false));
    }
    else
    {
        var errors = ModelState.Values.SelectMany(x => x.Errors);

        return Json(new { success = ModelState.IsValid, errors});
        //return View(valueType); orginal code
    }
}

原始代码的工作方式是:如果模型有效,则呈现不同的视图,如果不返回模型则显示错误。

现在我必须在这里使用ajax,因为我需要为ListBox添加动态编辑逻辑,以使客户能够从一个列表中选择并保存到另一个列表中。我的目的是通过ajax +模型发送选定的ID。

使用Ajax之后,此代码:

repository.SaveValueType(valueType);

这工作正常,我正在保存数据。在这里,我只需要添加保存我的ID表单列表框,但是...

下一行工作:

return View(RouteUrl.Save, new SaveCategoryType(repository.GetCategoryByTypeId(valueType.TypeId).IsSysParam, valueType.Value, false));

我发现 answer

  •   

    您无法返回视图

问题: 我该如何解决我的问题?我知道我无法通过 window.location 发送POST pass post data with window.location.href

编辑:

如果唯一的答案是像以前一样使用POST,那么如何将javascript数据保存到Model.Ids(保存到客户存储从另一个ListBox中选择的值的ListBox)中。我也认为那是不可能的。

查看:

@if (!Model.IsSysParam)
{
    <div class="row">
        <div class="col-5">
            <select id="lbProducts" class="form-control" asp-items="Model.Products" size="@Model.ListBoxSize" multiple></select>
            <label class="m-1">Lista Przedmiotów</label>
        </div>
        <div class="col-1 align-self-center">
            <div class="d-flex justify-content-center">
                <button id="addItems" class="btn btn-light mt-1" type="button"><i class="fa fa-long-arrow-right" aria-hidden="true"></i></button>
            </div>
        </div>
        <div class="col-5">
            <select id="lbAddedProducts" class="form-control" size="@Model.ListBoxSize" multiple></select>
            @*<button asp-page-handler="SaveValueItems" id="saveValueItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-floppy-o" aria-hidden="true"></i></button>*@
            <button id="removeItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
        </div>
    </div>
}

<form asp-route="@(Model.IsSysParam ? RouteUrl.Name.SystemList : RouteUrl.Name.CategoryList)" method="post">
        <div class="text-left">
            <input type="hidden" name="isSysParamCategory" value="@Model.IsSysParam.ToString()" />
            <button class="btn btn-secondary btn mt-1">Anuluj</button>
        </div>
    </form>

脚本

<script type="text/javascript">
    $(document).ready(function () {
        var itemList = $('select[id=lbProducts]');
        var addedItemList = $('select[id=lbAddedProducts]');

        var addItemsButton = $("button[id=addItems]");
        var removeItemsButton = $("button[id=removeItems]");
        var saveValueItems = $("button[id=saveValueItems]");
        var saveValue = $("button[id=saveValue]");

        $(addItemsButton).click(function () {
            var dItems = {};
            var dAddedItems = {};
            var dItemsToRemove = {};

            SelectedItems(dItems);
            AddedItem(dAddedItems);
            CheckItems(dAddedItems, dItemsToRemove, dItems);
            AddItemsToListBox(dItems);
        });

        function SelectedItems(dItems) {
            var selectedItems = $(itemList).find(':selected');
            for (var i = 0; i < selectedItems.length; i++) {
                var item = selectedItems[i];
                dItems[$(item).val()] = $(item).text();
            }
        };

        function AddedItem(dAddedItems) {
            var addedItems = $(addedItemList).find('option');
            for (var i = 0; i < addedItems.length; i++) {
                var item = addedItems[i];
                dAddedItems[$(item).val()] = $(item).text();
            }
        };

        function CheckItems(dAddedItems, dItemsToRemove, dItems) {
            for (var key in dAddedItems) {
                if (dItems.hasOwnProperty(key)) {
                    dItemsToRemove[key] = dItems[key];
                }
            };
            Remove(dItemsToRemove, dItems);
        };

        function Remove(dItemsToRemove, dItems) {
            for (var key in dItemsToRemove) {
                if (dItems.hasOwnProperty(key)) {
                    delete dItems[key];
                }
            };
        };

        function AddItemsToListBox(dItems) {
            $.each(dItems, function (key, value) {
                $(addedItemList).append($("<option></option>").attr("value", key).text(value));
            });
        };

        $(removeItemsButton).click(function () {
            RemoveSelectedItems();
        });

        function RemoveSelectedItems() {
            var removeSelectedItems = $(addedItemList).find(':selected');
            for (var i = 0; i < removeSelectedItems.length; i++) {
                removeSelectedItems[i].remove();
            }
        };

        $(saveValue).click(function () {
            var itemIds = '';
            var form = $('#editValueForm');

            var addedItems = $(addedItemList).find('option');
            for (var i = 0; i < addedItems.length; i++) {
                var item = addedItems[i];
                if (i == 0) { itemIds = $(item).val(); }
                else { itemIds += ',' + $(item).val(); }
            }


            var valueTypeEditViewModel = {
                ValueId: $('input[id=ValueType_ValueId]').val(),
                TypeId: $('input[id=ValueType_TypeId]').val(),
                Value: $('input[id=ValueType_Value]').val(),
                Code: $('input[id=ValueType_Code]').val(),
                Controller: $('input[id=ValueType_Controller]').val(),
                Description: $('input[id=ValueType_Description]').val(),
                sEditDate: $('label[id=ValueType_EditDate]').text(),
                sCreateDate: $('label[id=ValueType_CreateDate]').text(),
                IsSysParam: $('input[id=ValueType_IsSysParam]').val(),
                ItemIds: itemIds,
            };

            $.ajax({
                type: "POST",
                url: form.attr('action'),
                data: JSON.stringify(valueTypeEditViewModel),
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                contentType: "application/json",
                dataType: "json",
                success: function (response) {
                    if (response.success) {
                        console.log('spoko');
                    } else if (!response.success) {
                        //var validator = $(form).validate();
                        //validator.settings.rules
                        //validator.settings.messages
                        console.log('dupa');
                    };
                }
            });
        })
    });
</script>

1 个答案:

答案 0 :(得分:0)

$(saveValue).click(function () {
                var itemIds = '';
                var addedItems = $(addedItemList).find('option');
                for (var i = 0; i < addedItems.length; i++) {
                    var item = addedItems[i];
                    if (i == 0) { itemIds = $(item).val(); }
                    else { itemIds += ',' + $(item).val(); }
                }
                $('#ValueType_ItemIds').val(itemIds);
            })

我不知道是什么意思让我意味着我想在这里使用ajax :)隐藏的字段进来了,并帮助了我。在所有情况下都应该很明显,但我开始考虑并为自己做了一些不必要的并发症

<input type="hidden" asp-for="ValueType.ItemIds" />

我应得的更多否定词:)