Hi,
I have implemented Cascading (Dependent) DropDownList using ASP.Net MVC.
Now I need show alert message box after insert data and redirect on Index page in ASP.Net MVC.
To show alert message in asp.net mvc after insert data using store procedure from MySQL database, I have write the code like as shown below.
<script type="text/javascript">
$(function () {
var msg = '@ViewData["result"]';
if (msg > 0)
{
alert("User Details Inserted Successfully");
window.location.href = "@Url.Action("Index", "Home")";
}
});
</script>
The data is correctly registered in the database table and the alert message box after insert data it's show.
But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.
window.location.href = "@Url.Action("Index", "Home")";
I mean that all other (populated cascading) DropDownList are enabled but empty.
How to do resolve this?
Model
public class PersonModel
{
public PersonModel()
{
this.Countries = new List<SelectListItem>();
this.States = new List<SelectListItem>();
this.Cities = new List<SelectListItem>();
}
public List<SelectListItem> Countries { get; set; }
public List<SelectListItem> States { get; set; }
public List<SelectListItem> Cities { get; set; }
public int CountryId { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
}
Controller
public class HomeController : Controller
{
[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
var personModel = new PersonModel
{
Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
};
return View(personModel);
}
[HttpPost]
public ActionResult Index(PersonModel person)
{
Methodsqlinsert(person);
person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
if (ModelState.IsValid)
{
return View(person);
}
return View(person);
}
private void MTsqlinsert(PersonModel person)
{
try
{
string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
using (MySqlConnection con =
new MySqlConnection(constr))
{
using (MySqlCommand command =
new MySqlCommand("SP_INS", con))
{
command.Connection = con;
command.CommandType = CommandType.StoredProcedure;
con.Open();
command.Parameters.AddWithValue("tCountryId", person.CountryId);
command.Parameters.AddWithValue("tStateId", person.StateId);
command.Parameters.AddWithValue("tCityId", person.CityId);
ViewData["result"] = command.ExecuteNonQuery();
con.Close();
}
}
}
catch (Exception ex)
{
string message = string.Format("<b>Message:</b> {0}<br /><br />", ex.Message);
message += string.Format("<b>StackTrace:</b> {0}<br /><br />", ex.StackTrace.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>Source:</b> {0}<br /><br />", ex.Source.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>TargetSite:</b> {0}", ex.TargetSite.ToString().Replace(Environment.NewLine, string.Empty));
ModelState.AddModelError(string.Empty, message);
}
}
[HttpPost]
public JsonResult AjaxMethod(string type, int value)
{
PersonModel model = new PersonModel();
switch (type)
{
case "CountryId":
model.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + value, "StateName", "StateId");
break;
case "StateId":
model.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + value, "CityName", "CityId");
break;
}
return Json(model);
}
private static List<SelectListItem> PopulateDropDown(string query, string textColumn, string valueColumn)
{
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr[textColumn].ToString(),
Value = sdr[valueColumn].ToString()
});
}
}
con.Close();
}
}
return items;
}
}
View
@model Ins.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
.modalBackground {
position: fixed;
top: 0;
left: 0;
background-color: black;
z-index: 99;
opacity: 0.8;
filter: alpha(opacity=80);
-moz-opacity: 0.8;
min-height: 100%;
width: 100%;
}
.loading {
font-family: Arial;
font-size: 10pt;
border: 5px solid #67CFF5;
width: 200px;
height: 100px;
display: none;
position: fixed;
background-color: White;
z-index: 999;
}
</style>
</head>
<body>
<div class="loading" align="center">
Loading. Please wait.<br /><br />
<img alt="" src="~/Images/loader.gif" />
</div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownListFor(m => m.CountryId, Model.Countries, "Please select")
<br />
<br />
@Html.DropDownListFor(m => m.StateId, Model.States, "Please select")
<br />
<br />
@Html.DropDownListFor(m => m.CityId, Model.Cities, "Please select")
<br />
<br />
<input type="submit" value="Submit" />
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Scripts/DatePicker.js");
@Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
var msg = '@ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("Ok");
var url = "@Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
}
</body>
</html>