我想做的是从 Controller 返回一个对象,并在 Razor View 中一个一个地读取它的所有值。该值从 View 到 Controller 进展顺利;问题是当我尝试将它从 Controller 返回以查看时。我正在使用 ASP.NET、Razor Views (HTML5)、AJAX 和 JQuery。如果您需要有关此的更多信息,请告诉我。
这些是我在 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>
这是我的 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>
而且,这是我的 Controller 代码:
[HttpPost]
public JsonResult GetProductValue(string idProducto)
{
Producto producto = db.Producto.Find(Convert.ToInt32(idProducto));
if (producto == null)
{
producto = new Producto();
}
return Json(producto);
}
最佳答案
$.getJSON
使用 http GET
请求获取数据,而在您的 Controller 中您的操作方法是 POST
可以改成HttpGet
或者使用$.post
方法
关于c# - 我无法在 C# 中使用 Jquery 和 Ajax 从 Controller 向 Razor View 发送值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57157564/