gpt4 book ai didi

javascript - 使用ajax以mvc模式通过 Controller 发送数据

转载 作者:太空宇宙 更新时间:2023-11-03 20:51:53 25 4
gpt4 key购买 nike

我正在尝试使用 knockout 将数据从我的 UI 发送到 Controller 。这是用于发送我的 ajax 请求 (PUT) 的 javascript

var model = new Object();
model.StudentID = "";
model.ActiveProgram = "";
model.ProgramDesc = self.programData();
model.Cohorts = self.associationData();
model.LoadIntent = self.loadIntentData();
model.Francophone = self.frenchData();
model.Gender = self.genderData();

$.ajax({
url: putStudentRegRequirementsUrl,
type: "PUT",
contentType: jsonContentType,
dataType: "json",
data: JSON.stringify(model),
//jsonData:model,
success: function (data) {
$('#notificationHost').notificationCenter('addNotification', { message: "Updated.", type: "info" });
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status != 0)
{
$('#notificationHost').notificationCenter('addNotification', { message: "Unable to update registration requirement.", type: "error"});
}
}
});

但是当我调试它以查看我的 Controller 时,输入的字符串是空白的。这是我的 Controller

 [HttpPut]
public async Task<JsonResult> UpdateRegistrationRequirementAsync(string regRequirementJson)
{
try
{
var regRequirementModel = JsonConvert.DeserializeObject<RegistrationRequirement>(regRequirementJson);
var response = await ServiceClient.L09PutRegistrationRequirementAsync(CurrentUser.PersonId, regRequirementModel);
return Json(response);
}
catch( Exception ex)
{
Logger.Debug(ex, "Error updating Registration Requirement for user failed.");
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Error updating Registration Requirement.");
}
}

最佳答案

Action 将根据名称解析来自客户端的参数,因此您需要传递名称为 regRequirementJson 的参数,其中包含您的 json。所以改变这一行

data: JSON.stringify(model)

data: { regRequirementJson: JSON.stringify(model) }

并删除 contentType: jsonContentType

或者您可以尝试其他方式。由于 ASP.NET 可以自行反序列化 json,因此您可以保持 js 代码不变并将 Controller 更新为

[HttpPut]
public async Task<JsonResult> UpdateRegistrationRequirementAsync(RegistrationRequirement regRequirementModel )
{
try
{
var response = await ServiceClient.L09PutRegistrationRequirementAsync(CurrentUser.PersonId, regRequirementModel);
return Json(response);
}
catch( Exception ex)
{
Logger.Debug(ex, "Error updating Registration Requirement for user failed.");
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Error updating Registration Requirement.");
}

关于javascript - 使用ajax以mvc模式通过 Controller 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54408847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com