简体   繁体   中英

How to save dropdown list selected item value and listbox items value to database using jquery & ajax

I have a dropdown and listbox on screen and a save button.I need to save dropdown list selected item value and all items in listbox to database.Whenever i am saving only one record is saved inspite of sending multiple record.

This is my javascript code.

 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;
        }
    });
}

This is my method in controller to save to data base

    [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);
    }
} 

Table in database has NodeId,AssetId and LastUpdateDate column.

 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; }
}

Javascript code.

 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;
}

Method in controller

 [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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM