【发布时间】:2021-05-18 03:32:40
【问题描述】:
我想将 jquery ajax 中的多个值保存到 web api,请帮助我。 这是我的 asp.net 核心 web api 代码
[HttpPost]
public async Task<ActionResult<LeaveSubmit>> Submitdata([FromBody] LeaveSubmit myobj)
{
try
{
// string myobj = Convert.ToString(lobj);
JObject jsonObject = JObject.FromObject(myobj);
if (jsonObject == null)
{
return BadRequest();
}
else
{
var json = System.IO.File.ReadAllText(jsonFile);
var jsonObj = JObject.Parse(json);
var experienceArrary = jsonObj.GetValue("Notes") as JArray;
var newnotes = jsonObject;
experienceArrary.Add(newnotes);
jsonObj["Notes"] = experienceArrary;
string newJsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
System.IO.File.WriteAllText(jsonFile, newJsonResult);
// var response = await newJsonResult;
return Ok("Success");
}
}
catch (Exception ex)
{
this.telemetryClient.TrackException(ex);
return this.StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
jquery ajax 代码。我已经成功保存了一个名为 notes 的值,我想再保存一个值,但我无法传递其发送 null 的值,因此 api 使用 null 值保存了值
$("#btnSubmit").click(function () {
datapass();
});
function datapass() {
var values = { notes: $("#notesval").val() };
var myvalue = JSON.stringify(values);
//myvalue = "{"notes":""}", values = { notes: "" }
if (values == '{ notes: "" }' || myvalue == '{"notes":""}' || myvalue == null || values == null) {
return false;
}
else {
$.ajax({
url: window.location.origin + "/api/ServiceApi/Submitdata",
type: 'POST',
dataType: 'json',
data: myvalue,
contentType: 'application/json; charset=utf-8',
success: function (response) {
response = eval(response);
OnSuccess("Success");
//console.log("Savesuccessful");
//console.log(data);
},
error: function (error) {
alert("Save sucessfully.");
//console.log("My errror values:", error);
}
});
$("#confirm-modal").show();
}
}
【问题讨论】:
标签: jquery asp.net ajax api asp.net-core