使用 AJAX 传递模型和变量

Pass Model and Variables with AJAX

从主视图 (Category.cshtml) 调用局部视图 (_AddItem.cshtml),以便在加载时将现有项目添加到页面。

我现在添加 AJAX 以便用户可以通过单击按钮将项目添加到页面。当随后提交表单时,该项目将被添加到模型中。

局部视图依赖于类别模型(activeCategoryModel)和两个变量。目前,这些正在通过以下方式从视图中成功传递:

Category.cshtml


@Html.Partial(
    "_AddItem", 
    activeCategoryModel, 
    new ViewDataDictionary(ViewData) { { "itemIndex", itemIndex }, { "itemLabel", itemLabel } }
);

我的问题是如何在使用AJAX时传递模型(activeCategory)和这两个变量?下面是我开始为 AJAX post:

编写的代码

添加到视图的按钮和输入(Category.cshtml)


<input id="add-item-label" type="text" />
<input id="nextItemIndex" type="hidden" value="@activeCategoryModel.Items.Count" />
<button id="add-item" type="button">Add Item</button>

AJAX post 添加到 javascript

这不是必要的全功能代码,我只是尝试用 'data' 参数中的变量编写一个 AJAX post。


$("#add-item").click(function () {    
            var itemIndex = $("#nextItemIndex").val();  
            var itemLabel = $("#add-item-label").val();
            $.ajax({  
                type: "POST",  
                url: '@Url.Action("_AddItem")',  
                data: '{{itemIndex: ' + itemIndex + '}, {itemLabel: ' + itemLabel + '}}',  
                dataType: "json",  
                contentType: "application/json; charset=utf-8",  
                success: function () {  
                    $("#nextItemIndex").val($("#nextItemIndex").val() + 1);
                },  
                error: function () {  
                    alert("Error while adding item");  
                }  
            });  
            return false;  
        });  

部分视图调用已添加到 Controller

我认为这是部分视图调用中需要包含模型和变量的地方。


public ActionResult _AddItem(string itemIndex, string itemLabel)
        {
            
            return PartialView();
        }

局部视图(_AddItem.cshtml)

AJAX post.

没有更改

@model CategoryModel

@{ int i = (int)ViewData["itemIndex"];}
@{ string l = (string)ViewData["itemLabel"];}

...

在这种情况下有不同的方法,

示例Html.RenderPartial 直接渲染部分动作而没有 ajax。

If you want to use Ajax to call partialView , you must be render Html. Because PartialView returned Html.

我认为 Ajax 请求中最重要的值是 dataType 并且 第二个要点是在 div 元素

中添加了返回的 html 数据
jQuery("#add-item").click(function () {
              var dItemIndex = 1; //$("#nextItemIndex").val();
              var dItemLabel = "Text"; // $("#add-item-label").val();

            $.ajax({
                type: "POST",
                url: '@Url.Action("_AddItem","Home")',
                data: { itemIndex: dItemIndex, itemLabel: dItemLabel },
                dataType: "html",
                //contentType: "application/json; charset=utf-8",
                success: function (d) {
                    console.log("Success");
                    $("#partialData").html(d);
                   **// Create div in cshtml Page
                   // <div id="partialData"></div>**

                },
                error: function () {
                    alert("Error while adding item");
                }
            });
            return false;
        });

controller端可以读取参数并填写内容发送PartialView如下

 public ActionResult _AddItem(string itemIndex, string itemLabel)
        {
            ViewData["itemIndex"] = itemIndex;
            ViewData["itemLabel"] = itemLabel;
            return PartialView(new CategoryModel { Id = 5, Text = "Sample 5" });
        }