1

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm trying the solution, however when I put it in the dropdownlist it paints the entire text string, {id= 1, value = Loc} if i use data[i].id and data[i].value in the script send me "undefined" en the value
Okay. Just to clarify, are you now using '<option value=' + data[i].id+ '>' + data[i].value+ '</option > '. Sorry for the naming there, maybe it would be better to call 'value' asentamiento or something
I'm sorry, after a little researching I see I misunderstood a few things there about the SelectList and ViewBag. In order for this to work, you might have to do like @Phil Golding suggested and return just the drop2 list
Thank for you help, i changed the name ti data[i].id and data[i].value or data[i].asent (changing in the controller too) but if i dont use data[i].Text the result is undefined.
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>

4 Comments

It's also worth noting, that I don't entirely agree with returning the list items like this - personally you should have a class that maps to the data layer class, and return a list of that, rather than SelectListItems. It's then up to your front end application to do what it wants with the data.
Using this way, i get the list with the values in the controller, but in the view the script don´t show the values, don´t populate the dropdownlist.
Which option did you go for? Returning the Items property in the controller, or accessing the Items property in JS?
Returning the Items property in the controller works for me, only make some changes. Add the property Value and Text in the Query.
0

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 > ');
            }
        }
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.