[英]How can I retrieve “data” from jQuery Ajax on server side?
How can I retrieve the 'data' which is sent from a client? 如何检索从客户端发送的“数据”? (in field 'data')
(在“数据”字段中)
<script type="text/javascript">
$(function () {
$('#btnAddProductAjax').click(function () {
var name = $('#txtProductName').val();
var units = $('#txtUnitsInStock').val();
var price = $('#txtPrice').val();
$.ajax({
url: '@Url.Action("AddProductAjax", "Home")',
type: 'POST',
dataType: 'JSON',
data: {
productname: name,
unitsinstock: units,
price: price
},
success: function (data) {
$('#divResult').html(data);
alert('Product added successfully');
}
});
});
});
</script>
How can I use this data 我如何使用这些数据
data: {
productname: name,
unitsinstock: units,
price: price
},
in my server-side action 'AddProductAjax' ? 在我的服务器端操作'AddProductAjax'中?
public JsonResult AddProductAjax(string data)
{
//retrieve data which is sent from client and do something
return Json(json_data);
}
I tried : 我试过了 :
Googled for hours, no result 搜索了几个小时,没有结果
UPD: If I define action like UPD:如果我定义类似
AddProductAjax(string productname, int unitsinstock, decimal price)
- nothing happens. - 什么都没发生。 Ajax doesn't even call this action.
Ajax甚至没有调用此操作。 If I try
如果我尝试
AddProductAjax(string productname, string unitsinstock, string price)
- in debugger all the fields are empty! -在调试器中,所有字段均为空!
It helps to specify to MVC what type of request the action should expect using Attributes. 它有助于使用MAttributes向MVC指定操作应期望的请求类型。 Both the
HttpPost
and HttpGet
attributes are found in System.Web.Mvc
. HttpPost
和HttpGet
属性都可以在System.Web.Mvc
中找到。
Like this: 像这样:
[HttpPost]
public JsonResult AddProductAjax(string productname, int unitsinstock,
decimal price)
{
//logic...
return Json(json_data);
}
If it doesn't work at first, there is a chance you'll need to define the parameters (the variables in the parentheses) as string
s and then parse each one to retrieve the values inside, like so: 如果一开始不起作用,则可能需要将参数(括号中的变量)定义为
string
s,然后解析每个参数以检索其中的值,如下所示:
[HttpPost]
public JsonResult AddProductAjax(string productname, string unitsinstock,
string price)
{
int units = 0;
int.TryParse(unitsinstock, out units);
decimal decPrice = 0.00;
decimal.TryParse(price, out decPrice);
//logic...
return Json(json_data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.