DropDownList with java script

2019-08-03 18:34发布

问题:

I hope developers can support me, I have minimal experience in the use of java script.

After investigating and several attempts, I was able to load a dropdownlist with data from a LINQ query and pass as a parameter the value of a textbox.

What I could not do is from the query Linq get two fields (Id and value) send them to the dropdownlist and show the value but after being able to use the Id of that field to be able to use it in a create, currently I can only show the value but I need the Id too.

View

@Html.TextBox("CP", "", new { @id = "txtCP", @onchange = "FillOption();", @placeholder = "Codigo Postal" })
@Html.DropDownList("Asentamientos", ViewBag.Drop as List<SelectListItem>)

Script

<script>
    function FillOption() {
        var CP = $('#txtCP').val();
        $.ajax({
            type: "Post",
            url: "/Home/GetAsentamiento",
            data: { CP: CP },
            dataType: 'json',
            success: function (data) {
                $("#Asentamientos").empty();
                for (var i = 0; i < data.length; i++) {
                    $('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
                }
            }
        });
    }
</script>

Controllers

 public ActionResult Index()
        {
            List<SelectListItem> drop = new List<SelectListItem>
            {
            };
            ViewBag.Drop = drop;
            return View();

        }

        [HttpPost]
        public ActionResult GetAsentamiento(string CP)
        {
            var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select p.Asentamiento).ToList();
            SelectList lista = new SelectList(drop2);
            ViewBag.lista = lista;
            return Json(ViewBag.lista);
        }

I think of something like

 [HttpPost]
        public ActionResult GetAsentamiento(string CP)
        {
            var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
            SelectList lista = new SelectList(drop2);
            ViewBag.lista = lista;
            return Json(ViewBag.lista);
        }

but I do not know how the id and the value would be handled

Thanks

回答1:

If I understand your question correctly, I think you need to name the fields of the object you are creating with the Linq expression, so that it would look something like this:

[HttpPost]
    public ActionResult GetAsentamiento(string CP)
    {
        var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { id = p.IdCodigoPostal, value = p.Asentamiento}).ToList();
        SelectList lista = new SelectList(drop2);
        ViewBag.lista = lista;
        return Json(ViewBag.lista);
    }

Here are a few examples: https://code.msdn.microsoft.com/LINQ-to-DataSets-09787825#SelectAnonymousTypes1

Then you could access those fields from you javascript with data[i].id and data[i].value. I hope this helps.



回答2:

I suspect your issue is around pulling the data from the API result. You're setting the a new property in the ViewBag, then returning the ViewBag property. This really shouldn't be required, and you should instead just return your list, list so (Note: and SelectItemList has a property called "Items" which contains all items you've added):

 [HttpPost]
        public ActionResult GetAsentamiento(string CP)
        {
            var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
            SelectList lista = new SelectList(drop2);
            return Json(lista.Items);
        }

This should return just a nice list of ListItems. You could also just change your jQuery to loop through the items property, like so:

<script>
    function FillOption() {
        var CP = $('#txtCP').val();
        $.ajax({
            type: "Post",
            url: "/Home/GetAsentamiento",
            data: { CP: CP },
            dataType: 'json',
            success: function (data) {
                $("#Asentamientos").empty();
                for (var i = 0; i < data.Items.length; i++) {
                    $('#Asentamientos').append('<option value=' + data.Items[i].Value + '>' + data.Items[i].Text + '</option > ');
                }
            }
        });
    }
</script>


回答3:

Thanks to all, the code works as follows

Controller

 [HttpPost]
    public ActionResult GetAsentamiento(string CP)
    {
        var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { Value = p.IdCodigoPostal, Text= p.Asentamiento }).ToList();
        SelectList lista = new SelectList(drop2);
        return Json(lista.Items);
    }

Script

<script>
function FillOption() {
    var CP = $('#txtCP').val();
    $.ajax({
        type: "Post",
        url: "/Home/GetAsentamiento",
        data: { CP: CP },
        dataType: 'json',
        success: function (data) {
            $("#Asentamientos").empty();
            for (var i = 0; i < data.length; i++) {
                $('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
            }
        }
    });
}