我想通过post方法从我的视图发送我的ajax数据,但我不知道如何在控制器方法中接收它。这是ajax代码:
$.ajax({
contentType: 'application/json; charset=utf-8',
method: 'post',
async: false,
url: "Gateway/DB_Rola",
data:Obj,
success: function (Data) {alert("Good");},
error: function () {alert("Error");}
});
这是控制器代码:
[HttpPost] // bindig data with class thing
public JsonResult DB_Rola(thing things)
{ ... }
模态类代码:
public class thing
{
public int surah { get; set; }
public int ayah { get; set; }
public string verse { get; set; }
}
现在我不知道如何在控制器方法中获取该对象。我使用get
方法尝试过它,工作正常,问题出在post
...
答案 0 :(得分:2)
请尝试使用以下代码段。
<强> JS 强>
<script>
$(document).ready(function () {
var things = new Object();
things.surah = 1;
things.ayah = 2;
things.verse = "3";
$.ajax({
url: "Home/DB_Rola?count=" + 1,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: JSON.stringify(things),
success: function (result) {
alert('success');
},
error: function (result) {
alert('boo!');
},
});
});
</script>
<强> MODEL 强>
public class thing
{
public int surah { get; set; }
public int ayah { get; set; }
public string verse { get; set; }
}
<强> CONTROLLER 强>
public class HomeController : Controller
{
[HttpPost]
public ActionResult DB_Rola(thing things)
{
return Json(new { IsSuccess = true });
}
}
输出:
有/无计数
更新1:传递对象列表[]而不是单个对象事物
<script>
$(document).ready(function () {
var things = new Array();
var test1 = new Object();
test1.surah = 1;
test1.ayah = 2;
test1.verse = "3";
things.push(test1);
var test2 = new Object();
test2.surah = 11;
test2.ayah = 22;
test2.verse = "33";
things.push(test2);
$.ajax({
url: "Home/DB_Rola?count=" + 1,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: JSON.stringify(things),
success: function (result) {
alert('success');
},
error: function (result) {
alert('boo!');
},
});
});
</script>
[HttpPost]
public ActionResult DB_Rola(List<thing> things,int count)
{
return Json(new { IsSuccess = true });
}
答案 1 :(得分:0)
试试这只是一个例子,
function SearchProduct () {
var isExcluded = $('#chkisExcluded').is(':checked');
$.ajax({
type: "POST",
url: '@Url.Action("SearchProductManagement","ProductListManagement")',
data: { isExcluded: isExcluded,},
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
}
<强>控制器强>
public JsonResult SearchProductManagement(bool isExcluded)
{
//Your code
return Json(data, JsonRequestBehavior.AllowGet);
}
查看强>
<input type="button" value="Go" onclick="return SearchProduct();" class="button next" />
答案 2 :(得分:0)
假设Obj = {surah:somvalue, ayah:somevalue, verse:somevalue}
问题是额外的参数计数,你没有处理计数的post动作,
所以试试:
$.ajax({
contentType: 'application/json; charset=utf-8',
method: 'post',
async: false,
url: "Gateway/DB_Rola,
data:Obj,
success: function (Data) {alert("Good");},
error: function () {alert("Error");}
});