简体   繁体   English

通过Ajax调用将数据从asp.net MVC控制器传递到View

[英]Passing data from asp.net MVC controller to the View via Ajax call

Hello guys I have got some trouble with ajax that I try to understand what is going on. 大家好,我尝试使用Ajax遇到了一些麻烦,我想了解发生了什么。 Well I have got this controller which is returning list of Guider Model, well here is my Controller: 好吧,我有这个控制器,它正在返回Guider Model的列表,这是我的控制器:

[HttpGet]
        public JsonResult ShowGuiders(string latitude, string longitude)
        {
            double lat = DataTypeConvert.ConvertToDouble(latitude);
            double lon = DataTypeConvert.ConvertToDouble(longitude);
            GeoCoordinate geoCoordinateFrom = new GeoCoordinate(lat, lon);

            var nearbyGuiders = (from guider in db.Guiders.AsEnumerable()
                                 let distance = geoCoordinateFrom.GetDistanceTo(new GeoCoordinate(guider.Latitude.Value, guider.Longitude.Value))
                                 where distance <= 100000
                                 orderby distance ascending
                                 select guider).ToList();
            return Json(nearbyGuiders, JsonRequestBehavior.AllowGet);

        }

Here is my script: 这是我的脚本:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnGet").click(function () {
                var coordinate = {
                    "Latitude": $("#latitude").val(),
                    "Longitude": $("#longitude").val()
                };
                $.ajax({
                    type: 'GET',
                    url: '@Url.Action("ShowGuiders", "Guider")',
                    data: { latitude: coordinate.Latitude, longitude: coordinate.Longitude },
                    dataType: "json",
                    contentType: "application/json;charset=utf-8",
                    success: function (result) {
                        // Result
                        alert("Succes");
                    },
                    error: function (response) {
                        //do your own thing
                        alert("fail");
                    }
                });
            }); //end .submit()
        });
    </script>

Finally here is my Guider Model: 最后是我的指导者模型:

public class Guider
    {
        [Key]
        [ForeignKey("ApplicationUser")]
        public string GuiderID { get; set; }
        //code...
        public double? Latitude { get; set; }
        public double? Longitude { get; set; }
        public bool IsAccepted { get; set; }

        [ForeignKey("CancellationPolicy")]
        public int? CancellationPolicyID { get; set; }

        [ForeignKey("Premium")]
        public int? PremiumID { get; set; }

        public virtual Premium Premium { get; set; }
        public virtual CancellationPolicy CancellationPolicy { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }

        public virtual ICollection<UnavailableDate> UnavailableDates { get; set; }

    }

Well the problem was that whenever I was trying to return List of Guider nothing was happening and event of error function of ajax was raising. 很好的问题是,每当我尝试返回Guider列表时,都没有发生任何事情,而ajax的错误功能事件也在增加。 So I tried to return just an Object of Guider and evrything was working perfectly. 因此,我尝试只返回一个Guided对象,并且evrything运行良好。 This controller is working perfetcly: 该控制器正在正常运行:

[HttpGet]
        public JsonResult ShowGuiders(string latitude, string longitude)
        {

            myGuider.Country = "Greece";
            return Json(myGuider, JsonRequestBehavior.AllowGet);

        }

So I figured out that Json does not suport my object hierarchy. 因此,我发现Json不会支持我的对象层次结构。 So I solved my problem with anononymus objects. 所以我用匿名对象解决了我的问题。 I modified the controller like this, and I return propperties that I need : 我这样修改了控制器,并返回了所需的属性:

[HttpGet]
        public JsonResult ShowGuiders(string latitude, string longitude)
        {
            double lat = DataTypeConvert.ConvertToDouble(latitude);
            double lon = DataTypeConvert.ConvertToDouble(longitude);
            GeoCoordinate geoCoordinateFrom = new GeoCoordinate(lat, lon);

            var nearbyGuiders = (from guider in db.Guiders.AsEnumerable()
                                 let distance = geoCoordinateFrom.GetDistanceTo(new GeoCoordinate(guider.Latitude.Value, guider.Longitude.Value))
                                 where distance <= 100000
                                 orderby distance ascending
                                 select new { country = guider.Country } ).ToList();
            return Json(nearbyGuiders, JsonRequestBehavior.AllowGet);

        }

 $("#btnGet").click(function () { var coordinate = { "Latitude": $("#latitude").val(), "Longitude": $("#longitude").val() }; $.ajax({ type: 'GET', url: '@Url.Action("ShowGuiders", "Guider")', data: { latitude: coordinate.Latitude, longitude:coordinate.Longitude }, success: function (result) { // Result alert("Succes"); }, error: function (response) { //do your own thing alert("fail"); } }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM