用Json数据填充文本框

时间:2018-08-23 14:50:59

标签: json ajax asp.net-mvc-5

请参见下面的代码

控制器-

public ActionResult AmountOwed()
{
    int vehicleID = Convert.ToInt32(Request.Cookies["VehicleID"].Value);
    var amountOwed = _PUSPERSContext.TblEOYPayments.Where(x => x.VehicleID == vehicleID).OrderByDescending(x => x.PaymentID).Take(1).Select(x => x.AmountOwed).ToList().FirstOrDefault();  
    return Json(amountOwed, JsonRequestBehavior.AllowGet);
}

这给了我想要的值,但现在我想在文本框中以局部视图(_EOYPaymentsLayout.cshtml)来显示它-

<div class='form-group'>
    @Html.LabelFor(m => m.TblEOYPayment.AmountOwed, new { title = "Amount Owed" })
    @Html.TextBoxFor(m => m.TblEOYPayment.AmountOwed, new { title = "Amount Owed", @class = "form-control inputSizeMedium"})
</div>

我已经在ajax代码中尝试了各种方法,但是我永远无法将值获取到视图中(此代码在名为Payments的主视图中)-

$(document).ready(function () {
    $('#addEOYPayment').click(function () {
        $.ajax({
            type: "GET",
            url: "AmountOwed",
            datatype: "Json",
            success: function (data) {
                $('#TblEOYPayment_AmountOwed').html(data.amountOwed);
            }
        });
    });
});

将感谢您的一些建议。谢谢

3 个答案:

答案 0 :(得分:0)

您可以返回部分视图,而不是返回json对象

C#

public string FirstName { get; set; }
public string LastName { get; set; }

[NotMapped]
public string FullName { get;set };

js

    public ActionResult AmountOwed()
        {
            int vehicleID = 
            Convert.ToInt32(Request.Cookies["VehicleID"].Value);

            var amountOwed = _PUSPERSContext.TblEOYPayments.Where(x => x.VehicleID == vehicleID).OrderByDescending(x => x.PaymentID).Take(1).Select(x => x.AmountOwed).ToList().FirstOrDefault();

            return PartialView("NameOfView.cshtml", amountOwed );
        }

您的视图可能会收到欠款额的类型。

答案 1 :(得分:0)

您必须仔细检查您的网址。请输入控制器名称。例如:URL: "\Home\AmountOwed\" + ID,

答案 2 :(得分:0)

感谢您的答复。

最终使它工作了,就是这样:

$(document).ready(function () {

            $('#addEOYPayment').click(function () {
                $.ajax({
                    type: "GET",

                    url: "/Home/AmountOwed",

                    datatype: "Json",


                    success: function (data) {
                        $('#TblEOYPayment_AmountOwed').val(data);                     

                    }

                });


            });
        });