用服务器数组填充 jquery 数组

Fill jquery array with server array?

本文关键字:数组 jquery 填充 服务器      更新时间:2023-09-26

在控制器上,我有模型

 public partial class CategoryModel
{
...  
    public int[] SelectedCustomerIds { get; set; }
}

从控制器传递到视图。如何通过 Model.SelectedCustomerIds 填充 jquery 数组

 <script type="text/javascript">
        var selectedIds = [];  << what to replace here

你可以做的是,你可以先在jQuery中创建对象,然后使用AJAX对服务器进行ajax调用,服务器端你会得到这个对象,你可以简单地将该对象值转移到你的模型值!!

$.ajax({
                    type: "GET",        //GET or POST or PUT or DELETE verb
                    url: ajaxUrl,       // Location of the service
                    data: yourObject,       //Data sent to server
                    contentType: "",        // content type sent to server
                    dataType: "json",   //Expected data format from server
                    processdata: true,  //True or False
                    success: function (json) {//On Successful service call
                        var result = json.name;
                        $("#dvAjax").html(result);
                    },
                    error: ServiceFailed    // When Service call fails
                });

服务器端

using System.Web.Services;
    [WebMethod()]
    //[ScriptMethod()]
    public static void SendMessage(CategoryModel yourModelObject )
    {
    }
您可以使用

JSON.NET

<script type="text/javascript">
        var selectedIds = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.SelectedCustomerIds))

如果你想使用 JavaScript 端数组推送,那么试试这个在视图中将所有数组元素置于隐藏状态
@Html.Hidden("SelectedCustomerIds_"+i, Model.SelectedCustomerIds[i]) 和在JavaScript中

var selectedCustomerIds = [];
       $('*[id*=SelectedCustomerIds_]').each(function () {
        selectedCustomerIds.push($(this).val());
    });
 });