【发布时间】:2019-01-08 02:23:18
【问题描述】:
我在屏幕上有一个下拉列表框和一个保存按钮。我需要将下拉列表中的选定项目值和列表框中的所有项目保存到数据库中。每当我保存时,尽管发送了多条记录,但只保存一条记录。
这是我的 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; }
}
【问题讨论】:
-
关于您的 ajax 调用的问题。在错误函数中你有
else if (xhr.status == 200) { showSuccessMessage(" save successfully"); }为什么?如果是错误,那就不行了,我错了吗?
标签: c# jquery asp.net ajax asp.net-web-api