[英]I can't send a value to a Razor View from controller using Jquery and Ajax in C#
What I'm trying to do is to return an object from the controller and read all its values one by one in a razor view.我想要做的是从控制器返回一个对象并在剃刀视图中一个一个地读取它的所有值。 The value is going well from view to controller;
该值从视图到控制器进展顺利; the issue is when I try to return it from the controller to view.
问题是当我尝试从控制器返回它进行查看时。 I'm using ASP.NET, Razor Views (HTML5), AJAX and JQuery.
我正在使用 ASP.NET、Razor 视图 (HTML5)、AJAX 和 JQuery。 Please, let me know if you need further information about this.
如果您需要有关此的更多信息,请告诉我。
These are my three controls in the view:这些是我在视图中的三个控件:
<div class="form-group">
@Html.LabelFor(model => model.IdProducto, "IdProducto", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("IdProducto", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.IdProducto, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CantidadProducto, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CantidadProducto, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CantidadProducto, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ValorTotal, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ValorTotal, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ValorTotal, "", new { @class = "text-danger" })
</div>
</div>
This is my JQuery statement:这是我的 JQuery 语句:
<script type="text/javascript">
$(function () {
$('#IdProducto, #CantidadProducto').on('change', function () {
var IdProducto = $('#IdProducto').val();
var CantidadProducto = $('#CantidadProducto').val();
if (CantidadProducto.length > 0) {
$.getJSON('@Url.Action("GetProductValue")', { idProducto: IdProducto }, function (data) {
$.each(data, function (i, item) {
$('#ValorTotal').val(( Number(CantidadProducto) * Number(item.Precio) ));
});
});
}
else {
$('#ValorTotal').val(0);
};
});
});
</script>
And, this is my controller code:而且,这是我的控制器代码:
[HttpPost]
public JsonResult GetProductValue(string idProducto)
{
Producto producto = db.Producto.Find(Convert.ToInt32(idProducto));
if (producto == null)
{
producto = new Producto();
}
return Json(producto);
}
$.getJSON
fetchs data using http GET
request while in your controller your action method is POST
$.getJSON
使用 http GET
请求获取数据,而在您的控制器中,您的操作方法是POST
You can change it to HttpGet
or use $.post
method您可以将其更改为
HttpGet
或使用$.post
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.