首页 > 解决方案 > 为什么 ajax 结果,导致 mvc 视图中未定义的值?

问题描述

我想通过三个字段搜索并使用 ajax json jQuery 从数据库中检索数据,但是当我单击按钮搜索时,它会导致未定义值,如最后的图像中所示。我不知道是什么问题,在 json 动作或 ajax 脚本中,任何人都可以帮助我。

以下是我的模型:

 public class DonorOnline
{
    public int Id { get; set; }
    [Required]
    [StringLength(20, ErrorMessage = "لايمكن ان يزيد طول الاسم عن 20 حرف")]
    [Display(Name = "اسم المتبرع")]
    public string Name { get; set; }
    [Required(ErrorMessage = "اختر الدولة")]
    public int StateId { get; set; }
    [Required(ErrorMessage = "اختر المدينة")]
    public string CityName { get; set; }
    [Phone]
    [Required(ErrorMessage = "يجب ادخال رقم الهاتف")]
    [Display(Name = "رقم الهاتف")]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{3})$", ErrorMessage = "رقم الهاتف غير صحيح")]
    public string PhoneNumber { get; set; }
    [Required(ErrorMessage = "اختر فصيلة الدم")]
    [Display(Name = " فصيلة الدم")]
    public string bloodType { get; set; }
    [DataType(DataType.EmailAddress)]
    [Display(Name = "البريد الالكتروني")]
    public string Email { get; set; }
    [Display(Name = "طريقة الاتصال")]
    public connectionWay conn { get; set; }
    //public bool connIsMessage { get; set; }
    //public bool connIsCall { get; set; }
    //public bool MessageAndCall { get; set; }
    [Display(Name = "وقت الاتصال")]
    public string Tconn { get; set; }
    [ForeignKey("StateId")]
    public State state { get; set; }
    //[ForeignKey("CityId")]
    //public virtual City dcity { get; set; }

    public string adress {
        get
        {
            return state.StateName + "-" + CityName;
        }
            }
}

这是我在 DonorOlines Controller 中的操作:

 public ActionResult GetDonators()
    {
        ViewBag.StateId = new SelectList(db.states, "StateId", "StateName");
        ViewBag.CityName = new SelectList(db.cities, "CityId", "CityName");
        //var result = from a in db.Donors select a;
        return View();
    }

    }
    public JsonResult GetDonatorsWithParameter(int? StateId, string CityName, string blt)
    {

        ViewBag.StateId = new SelectList(db.states, "StateId", "StateName");
        ViewBag.CityName = new SelectList(db.cities, "CityId", "CityName");



        return this.Json(new
        {
            result = (from a in db.Donors
                      where (a.StateId == StateId && a.CityName == CityName && a.bloodType == blt)
                      select new { Id = a.Id, Name = a.Name, adress =( a.state.StateName+"-"+ a.CityName), PhoneNumber = a.PhoneNumber, bloodType = a.bloodType,Email=a.Email, conn = a.conn, Tconn = a.Tconn }).ToList()
        }, JsonRequestBehavior.AllowGet);
    }

这是我的观点:

 <div class="container" id="con">
<br />
     <div class="form-group row">
         &nbsp;&nbsp;
         الدولة: @Html.DropDownList("StateId", (SelectList)ViewBag.StateId, "اختر الدولة", htmlAttributes: new { @class = "form-control mx-2 col-md-2", id = "State" })
         المدينة:@Html.DropDownList("CityName", new SelectList(string.Empty, "Value", "Text"), htmlAttributes: new { @class = "form-control col-md-2", id = "city" })
         فصيلة الدم:@Html.DropDownList("blt", new SelectList(new[] { "+A", "-A", "+B", "-B", "+AB", "-AB", "+O", "-O" }), "اختر فصيلة الدم", new { @class = "form-control col-md-2 mr-md-3", id = "bt" })
         <input type="submit" value="Search" class="btn btn-info col-md-1 mr-1" id="btn1" />
         @*<input type="submit" value=" بحث" class="btn btn-info col-md-1" id="btnAllUser" />*@

     </div>
</div>



<div id="UpdatePanel">

</div>

这是我的 jQuery 脚本:

@section Scripts {
<script type="text/jscript">
$(function () {
    $('#State').change(function () {
        $.getJSON('/Donators/Citylist/' + $('#State').val(), function (obj) {
            var items = '<option>اختر المدينة</option>';
            $.each(obj, function (i, city) {
                items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
            });
            $('#city').html(items);
        });
    });

   
// this will use for Get Data based on parameter
$("#btn1").click(function () {
    $.ajax({
        url: "@Url.Action("GetDonatorsWithParameter", "DonorOnlines")",
        data: {
            StateId: $('#State').val(),
            CityName: $('#city').val(),
            blt: $('#bt').val()
        },
    type: "GET",
    dataType: "json",
    success: function (data) {
        loadData(data);
    },
    error: function () {
        alert("Failed! Please try again.");
    }
});
});

function loadData(data) {
    // Here we will format & load/show data
    var tab = $('<table class="table"></table>');
    var thead = $('<thead></thead>');
    thead.append('<th>User ID</th>');
    thead.append('<th>User name</th>');
    thead.append('<th>Address</th>');
    thead.append('<th>Phone</th>');
    thead.append('<th>bloodType</th>');
    thead.append('<th>Email</th>');
    thead.append('<th>Connection way</th>');
    thead.append('<th>time</th>');

    tab.append(thead);
    $.each(data, function (r, val) {
        // Append database data here
        var trow = $('<tr></tr>');
        trow.append('<td>' + val.Id + '</td>');
        trow.append('<td>' + val.Name + '</td>');
        trow.append('<td>' + val.adress + '</td>');
        trow.append('<td>' + val.PhoneNumber + '</td>');
        trow.append('<td>' + val.bloodType + '</td>');
        trow.append('<td>' + val.Email + '</td>');
        trow.append('<td>' + val.conn + '</td>');
        trow.append('<td>' + val.Tconn + '</td>');

        tab.append(trow);
    });
    $("tr:odd", tab).css('background-color', '#C4C4C4');
    $("#UpdatePanel").html(tab);
};


});
</script>

}

GetDonators 视图:

标签: jqueryajaxasp.net-mvc-5ef-code-first

解决方案


推荐阅读