簡體   English   中英

我無法在 C# 中使用 Jquery 和 Ajax 從控制器向 Razor 視圖發送值

[英]I can't send a value to a Razor View from controller using Jquery and Ajax in C#

我想要做的是從控制器返回一個對象並在剃刀視圖中一個一個地讀取它的所有值。 該值從視圖到控制器進展順利; 問題是當我嘗試從控制器返回它進行查看時。 我正在使用 ASP.NET、Razor 視圖 (HTML5)、AJAX 和 JQuery。 如果您需要有關此的更多信息,請告訴我。

這些是我在視圖中的三個控件:

        <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>

而且,這是我的控制器代碼:

[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請求獲取數據,而在您的控制器中,您的操作方法是POST

您可以將其更改為HttpGet或使用$.post方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM