我正在研究MVC应用程序。我试图通过JQuery将参数从视图传递到控制器使用JSON。返回类型工作正常但是当我传递参数时它失败了。以下是代码
查看
<script type="text/javascript">
$(document).ready(function () {
$("#ClientList").change(function () {
$.ajax({
url: '@Url.Action("GetClientData", "Home")',
type: 'Post',
dataType: 'json',
data: { clientID: $("#CientList").val() },
contentType: 'application/json; character=utf-8',
success: function (data) {
if (data.success) {
document.getElementById("ClientName").value = data.clientName
}
else {
alert('invalid ID' + data.success);
}
}
});
});
});
CONTROLLER
[HttpPost]
public JsonResult GetClientData(string clientID)
{
Client client = Client.GetClient(Convert.ToInt32(clientID));
if (client != null)
{
return Json(new { success = true, clientName = client.ClientName });
}
return Json(new { success = false });
}
如果我从控制器代码中取出参数。它工作正常但是当方法接受参数时失败。有什么建议吗?
答案 0 :(得分:0)
<script type="text/javascript">
$(document).ready(function () {
$("#ClientList").change(function () {
var selectedClientID = { clientID: $("#ClientList").val() };
$.ajax({
url: '@Url.Action("GetClientData", "Home")',
type: 'Post',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(selectedClientID),
success: function (data) {
if (data.success) {
document.getElementById("ClientName").value = data.clientName;
document.getElementById("ClientAddress").value = data.clientAddress;
document.getElementById("ClientContactNumber").value = data.clientContact;
}
else {
alert('invalid ID' + data.success);
}
}
});
});
});
</script>
这完美无缺