如何使用jquery和ajax将下拉列表中的选定项目值和列表框项目值保存到数据库

时间:2018-07-31 16:00:49

标签: c# jquery asp.net ajax asp.net-web-api

我在屏幕上有一个下拉列表框和一个保存按钮。我需要将下拉列表中选中的项目值和列表框中的所有项目保存到数据库中。每当我保存时,尽管发送了多条记录,也只保存了一条记录。

这是我的JavaScript代码。

 function SaveNodeAsset() {
    debugger;
    var urladdress = $('#hfwebApiurl').val() +"/NodeAssets/InsertNodeAssets";
    var NodeId = $("#ddlNode").val();
    var Asset = [];
    $('#lbRight option').each(function () {
        var AssetId = $(this).val();
        var items = {"NodeId": NodeId ,"AssetId": AssetId };
        Asset.push(items);
    });
    console.log(Asset);

    $.ajax({
        type: "Post",
        url: urladdress,
        data: "{Asset:" + JSON.stringify(Asset) + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function a(r) {
            console.log(r);
        },

        error: function (xhr, errorType, exception) {
            console.log(xhr);
            if (xhr.status == 409) {
                showErrorMessage("already Exist");
            }
            else if (xhr.status == 200) {
                showSuccessMessage(" save successfully");
            }
            console.log('error');
            return false;
        }
    });
}

这是我在控制器中保存到数据库的方法

    [HttpPost]
    public HttpResponseMessage InsertNodeAssets(JObject ns)
    {
        try
        {
            using (DTO.IOTAModel context = new DTO.IOTAModel())
            {

               for(int i=0;i<=ns.Count;i++)
                {

                    DTO.NodeAssets lvNodeAsset = new DTO.NodeAssets();

                    lvNodeAsset.AssetId = Convert.ToInt32((string)ns["Asset"][i]["AssetId"]);
                    lvNodeAsset.NodeId = Convert.ToInt32((string)ns["Asset"][i]["NodeId"]);
                    lvNodeAsset.LastUpdateDate = DateTime.Now;

                    context.NodeAssets.Add(lvNodeAsset);
                    context.SaveChanges();
                    return this.Request.CreateResponse(HttpStatusCode.OK);
                }
            }
        }
        catch (Exception ex)
        {
            log.Error("", ex);

        }
        return this.Request.CreateResponse(HttpStatusCode.ExpectationFailed);
    }
} 

数据库中的表具有NodeId,AssetId和LastUpdateDate列。

 public class NodeAssets
{
    public NodeAssets();

    public int AssetId { get; set; }
    public DateTime? LastUpdateDate { get; set; }
    [Key]
    public int NodeAssetId { get; set; }
    public int NodeId { get; set; }
}

1 个答案:

答案 0 :(得分:0)

JavaScript代码。

 function SaveNodeAsset() {
    //debugger;
    var urladdress = $('#hfwebApiurl').val() + "/NodeAssets/InsertNodeAssets";
    var NodeId = $("#ddlNode").val();
    var Asset = [];
    $('#lbRight option').each(function () {
        var AssetId = $(this).val();
        Asset.push(AssetId);
    });

    var ArrayAsset = Asset.join(",");

    $.ajax({
        type: "Post",
        url: urladdress + "?NodeID=" + NodeId + "&AssetID=" + ArrayAsset,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function a(r) {
            debugger;
            console.log(r);
            if (r == 0) {
                showErrorMessage("Not Added Successfully");
            }
        },
        error: function (xhr, errorType, exception) {
            console.log(xhr);
            if (xhr.status == 409) {
                showErrorMessage("already Exist");
            }
            else if (xhr.status == 200) {
                showSuccessMessage(" save successfully");
            }
            console.log('error');
            //return false;
        }
    });
    return false;
}

控制器中的方法

 [HttpPost]
    public HttpResponseMessage InsertNodeAssets(int NodeID, string AssetID)
    {
        var AssetArray = AssetID.Split(',');
        try
        {
            foreach (var item in AssetArray)
            {
                using (DTO.IOTAModel context = new DTO.IOTAModel())
                {
                    DTO.NodeAssets lvNodeAsset = new DTO.NodeAssets();
                    lvNodeAsset.AssetId = Convert.ToInt32(item);
                    lvNodeAsset.NodeId = NodeID;
                    lvNodeAsset.LastUpdateDate = DateTime.Now;
                    context.NodeAssets.Add(lvNodeAsset);
                    context.SaveChanges();
                }

            }
            return this.Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (Exception ex)
        {
            log.Error("", ex);
            return this.Request.CreateResponse(HttpStatusCode.ExpectationFailed);
        }
    }
}