Hi,
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";
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();
model.States = PopulateDropDown(" SELECT * FROM `tbl_1` " +
" WHERE `Node_Code` = '" + value + "';", "Node_Name", "Node_Code");
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)
{
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;
}