首页 > 解决方案 > 如何使用javascript将jsonresult绑定到mvc中的标签文本

问题描述

我正在尝试将 jsonresult 数据绑定到来自数据库的标签文本,但它不起作用。我已经发布了脚本代码,它将获取下拉列表选择的值并传递给 actionresult,然后结果数据作为 jsonresult 传递

<script>
        function getOutletDetails() {
            debugger;
            var centreName = $("#ddl_Outlet").find("option:selected").text();

            $.ajax
                ({
                    url: "@Url.Action("OutletDetails", "AddTickets", new {area="Common"})",
                    type: 'POST',
                    datatype: 'application/json',
                    contentType: 'application/json',
                    data: JSON.stringify({ centreName: +centreName }),
                    success: function (result) {

                        $("#lblTelephone1").text(result.Telephone_01);                     

                    },
                    error: function () {
                        alert("Whooaaa! Something went wrong..")
                    },
                });
        }

    </script>

控制器代码

 [HttpPost]
        public ActionResult OutletDetails(string centreName)
        {

            List<tbl_Centre> lstcity = new List<tbl_Centre>();
          //  int id1 = Convert.ToInt32(id);
            //ViewBag.Id = id;
            lstcity = (objbs.CentreBs.GetAll().Where(x => x.CentreName == centreName)).ToList<tbl_Centre>();

            var result = JsonConvert.SerializeObject(lstcity, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });


            return Json(result, JsonRequestBehavior.AllowGet);

        }

标签: javascriptmodel-view-controllerjsonresult

解决方案


通常.text()会这样工作

$('#sampleButton').click(function(){
   $('#SampleId').text($('.userInput').val());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label id="SampleId">Sample text</label><br><br>

<input class="userInput" style="width: 300px" type="text" value="new value that will be replace at label"><br><br>

<button id="sampleButton">change label text</button>


推荐阅读