简体   繁体   English

$ .ajax成功:值始终未定义

[英]$.ajax success: value is always undefined

Why is the value to the 'c' object's member always 'undefined' in the javascript function UpdateFields()? 为什么javascript函数UpdateFields()中'c'对象成员的值总是'undefined'?

If I trap the json return in the controller listCities does have the values I would expect. 如果我在控制器listCities中捕获json返回确实具有我期望的值。 listCities is correctly populated at the return. listCities在返回时正确填充。

CityModel.cs CityModel.cs

namespace AutoCompleteInMVCJson.Models
{
    public class CityModel
    {
        public int Id { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
    }
}

HomeController.cs HomeController.cs

namespace AutoCompleteInMVCJson.Controllers
{
    public class HomeController : Controller
    {

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(string s)
        {

            List<CityModel> cities = new List<CityModel>()
            {
                new CityModel {Id=1, City="Cincinnati", State="Ohio", Zip="c-oh" },
                new CityModel {Id=2, City="Miami", State="Florida", Zip="33114" },
                new CityModel {Id=3, City="Miami", State="Florida", Zip="33125" },
                new CityModel {Id=4, City="Atlanta", State="Georgia", Zip="a-ga" },
                new CityModel {Id=5, City="Chicago", State="Illinois", Zip="c-il"},
                new CityModel {Id=6, City="Seattle", State="Washington", Zip="s-wa"},
                new CityModel {Id=7, City="Culabra", State="Puerto Rico", Zip="c-pr" },
                new CityModel {Id=8, City="Key West", State="Flordia", Zip="kw-fl" }
            };

            var listCities = (
                    from c in cities
                    where c.City.ToUpper().Contains(s.ToUpper())
                    select new { c.Id, c.City, c.State, c.Zip }
                );
            return Json(listCities, JsonRequestBehavior.AllowGet);
        }
    }
}

index.cshtml @model AutoCompleteInMVCJson.Models.CityModel index.cshtml @model AutoCompleteInMVCJson.Models.CityModel

@{
    ViewBag.Title = "";
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#City").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/Index",
                    type: "POST",
                    dataType: "json",
                    data: { s: request.term },
                    success: function (lst) {
                        response($.map(lst, function (c) {
                            return { label: c.Id + "//" + c.City + "//" + c.State + "//" + c.Zip, value: c.City };
                        }))
                    }
                })
            },
            messages: { noResults: "", results: function () { return (""); } }
        });
    })
</script>



@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <hr />
        <div class="form-group">
            <div class="col-md-12">
                @Html.TextBoxFor(m => m.Id, new { @class = "hidden" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-12">
                @Html.TextBoxFor(m => m.City, new { @class = "form-control" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-12">
                @Html.TextBox("State")
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-12">
               @Html.TextBox("Zip")
           </div>
       </div>
    </div>
}


<script type="text/javascript">
    var x = document.getElementById('City');

    x.addEventListener("blur", UpDateFields, true);

    function UpDateFields() {
        $.ajax({
            url: "/Home/Index"
            , type: 'post'
            , data: { s: $('#City').val() }
            , success: function (c) {
                $('#Id').val(c.Id);
                $('#State').val(c.State);
                $('#Zip').val(c.Zip);
                alert("//" + c.Id.val() + "//" + c.City + "//" + c.State + "//" + c.Zip + "//")
            }
        });
    }
</script>

If you can get what I'm trying to do here and have thougnts on a better way to get it done them I all ears. 如果你能得到我在这里想要做的事情并且想要更好地完成它们,我会全力以赴。

Thanks. 谢谢。

Your linq query is always going to return a list, even when there is only one item matched. 您的linq查询总是会返回一个列表,即使只有一个项匹配。

You make two ajax calls to /Home/Index. 你对/ Home / Index进行了两次ajax调用。 In the first case you rightly handle the returned json list: 在第一种情况下,您正确处理返回的json列表:

   success: function (lst) {
                        response($.map(lst, function (c) {
                            return { label: c.Id + "//" + c.City + "//" + c.State + "//" + c.Zip, value: c.City };
                        }))
                    }

In the second case you expect a single json object, which isn't what comes back. 在第二种情况下,你期望一个json对象,这不是回来的东西。

 success: function (c) {
                $('#Id').val(c.Id);
                $('#State').val(c.State);
                $('#Zip').val(c.Zip);
                alert("//" + c.Id.val() + "//" + c.City + "//" + c.State + "//" + c.Zip + "//")
            }

You need to handle the list in the second case too. 您还需要在第二种情况下处理列表。

On a side note: Why are you using a POST to handle a read only operation? 旁注:为什么使用POST来处理只读操作?

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

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