0

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

enter image description here

8
  • You are not doing anything with GetGps(value);'s returned value in your AjaxMethod, I suspect this is (at least part of) your problem. Unrelatedly, you seem to be mixing states and fruits Commented Nov 30, 2020 at 15:02
  • thanks for reply. with GetGps(value); it shouldn't pass the variable to query and populate the textbox? Commented Nov 30, 2020 at 15:06
  • GetGpsById returns a string, therefore GetGps returns a Json object with that string result, but you do nothing with it in your AjaxMethod. Also in your javascript, success part, you call PopulateDropDown("#CityId", list) but list doesn't seem to be set anywhere Commented Nov 30, 2020 at 15:12
  • I'm sorry for javascript is error copy/paste, I have edit the question list = response.Cities;. how to do resolve this? Commented Nov 30, 2020 at 15:15
  • Well then first add a Cities property in your PersonModel, and consider filling it in the AjaxMethod before returning it (like model.Cities = … then return Json(model);) Commented Nov 30, 2020 at 15:19

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, please see img in the question. now in textbox I have System.Web.Mvc.JsonResult value
Yes, this is because you set model.GPS = GetGps(value); instead of GetGps**ById**(value)

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.