简体   繁体   中英

Populate a textbox based on selected value from cascading dropdown using ASP.NET MVC

I tried to search posts, without any result either, maybe I didn't use the right words.

I am using ASP.NET MVC to create a webpage with a form.

The form has a two dropdownlist and a textbox .

The first dropdownlist is populated with values from the database.

The second dropdownlist is populated with values cascading, based on the selected first dropdownlist value.

The textbox will populate with a value from the same table and the second dropdownlist , based on the selected second dropdownlist value.

I have tried call a function from my controller inside of my view, without success. Don't have error but the textbox is empty.

Please, can you help me.

My code below

View

@Html.DropDownListFor(m => m.StateId, Model.States, "Select", new { @id = "StateId", @Class = "textarea" })
@Html.TextBoxFor(m => m.GPS, new { @Class = "textarea", placeholder = "GPS" })

@section Scripts {

    @Scripts.Render("~/bundles/jqueryui")
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/DatePicker.js");
    @Styles.Render("~/Content/cssjqryUi")

    <script type="text/javascript">
        $(function () {
            $('[id*=StateId]').on('change', function () {
                var fruitId = $(this).find("option:selected").val();
                if (fruitId != "") {
                    $.ajax({
                        type: "POST",
                        url: "/Home/GetFruitName",
                        data: "id=" + fruitId,
                        success: function (response) {
                            if (response != "") {
                                $('[id*=GPS]').val(response);
                            } else {
                                $('[id*=GPS]').val('');
                            }
                        }
                    });
                } else {
                    $('[id*=GPS]').val('');
                }
            });
        });

        $(function () {
            $("select").each(function () {
                if ($(this).find("option").length <= 1) {
                    $(this).attr("disabled", "disabled");
                }
            });

            $("select").change(function () {
                var value = 0;
                if ($(this).val() != "") {
                    value = $(this).val();
                }
                var id = $(this).attr("id");
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: '{type: "' + id + '", value: "' + value + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var dropDownId;
                        var list;
                        switch (id) {

                                case "StateId":
                                dropDownId = "#CityId";
                                list = response.Cities;
                                PopulateDropDown("#CityId", list);

                                break;
                        }

                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });

        function DisableDropDown(dropDownId) {
            $(dropDownId).attr("disabled", "disabled");
            $(dropDownId).empty().append('<option selected="selected" value="">Select</option>');
        }

        function PopulateDropDown(dropDownId, list) {
            if (list != null && list.length > 0) {
                $(dropDownId).removeAttr("disabled");
                $.each(list, function () {
                    $(dropDownId).append($("<option>/option>").val(this['Value']).html(this['Text']));
                });
            }
        } 
    </script>
}

Models

[Required]
[Display(Name = "StateId")]
public string StateId { get; set; }

[Required]
[Display(Name = "States")]
public List<SelectListItem> States = new List<SelectListItem>();

public string value { get; set; }

Controller

    public JsonResult AjaxMethod(string type, string value)
    {
        PersonModel model = new PersonModel();
        
        //Second DropDownList
        model.States = PopulateDropDown(" SELECT * FROM `tbl_1` " +
            " WHERE `Node_Code` = '" + value + "';", "Node_Name", "Node_Code");

        //GET value tod textbox GPS
        GetGps(value);

        return Json(model);
    }


    public JsonResult GetGps(string value)
    {
        return Json(GetGpsById(value), JsonRequestBehavior.AllowGet);
    }

    private static string GetGpsById(string value)
    {
        string sql;
        List<SelectListItem> items = new List<SelectListItem>();
        string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
        using (MySqlConnection con = new MySqlConnection(constr))
        {
            sql = string.Format("SELECT CONCAT(`LAT`, ' - ', `LON`) AS GPS FROM `tbl_1` WHERE Node_Code = @Id");
            using (MySqlCommand cmd = new MySqlCommand(sql))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Id", value);
                con.Open();
                string name = Convert.ToString(cmd.ExecuteScalar());
                con.Close();

                return name;
            }
        }
    }

    [HttpPost]
    public ActionResult Index(PersonModel person)
    {
       //First DropDownList            
       person.Countries = PopulateDropDown(" SELECT * FROM `tbl_master`;", "Name_City", "Name_code");

        return View(person);
    }

    private static List<SelectListItem> PopulateDropDown(string query, string textColumn, string valueColumn)
    {
        List<SelectListItem> items = new List<SelectListItem>();
        string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
        using (MySqlConnection con = new MySqlConnection(constr))
        {
            using (MySqlCommand cmd = new MySqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (MySqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        items.Add(new SelectListItem
                        {
                            Text = sdr[textColumn].ToString(),
                            Value = sdr[valueColumn].ToString()
                        });
                    }
                }
                con.Close();
            }
        }

        return items;
    }

Update

    public JsonResult AjaxMethod(string type, string value)
    {
        PersonModel model = new PersonModel();
        
        //Second DropDownList
        model.Cities = PopulateDropDown(" SELECT * FROM `tbl_1` " +
            " WHERE `Node_Code` = '" + value + "';", "Node_Name", "Node_Code");

        //GET value tod textbox GPS
        model.GPS = GetGps(value).ToString();

        return Json(model);
    }

在此处输入图像描述

Your problem is you never use the GPS property of your model:

success: function (response) {
    var dropDownId;
    var list;
    switch (id) {
        case "StateId":
          dropDownId = "#CityId";
          list = response.Cities;
          PopulateDropDown(dropDownId, list); // You set dropDownId, might as well use it
          $("#GPS").val(response.GPS); // Added to set text in textbox
          break;
    }
}

and in your controller,

model.GPS = GetGpsById(value); // this is already a string

instead of

model.GPS = GetGps(value).ToString(); // this is the string representation of a jsonified string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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