[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult create(n_userdata userdata)
{
List<n_country> allcountry = new List<n_country>();
List<n_state> allstate = new List<n_state>();
List<n_city> allcity = new List<n_city>();
using (nyalkaranEntities db = new nyalkaranEntities())
{
allcountry = db.n_country.OrderBy(v => v.countryname).ToList();
if(userdata !=null && userdata.countryid>0)
{
allstate = db.n_state.Where(a => a.countryid.Equals(userdata.countryid)).OrderBy(a => a.state).ToList();
}
}
ViewBag.countryid = new SelectList(allcountry, "countryid", "countryname",userdata.countryid);
ViewBag.stateid = new SelectList(allstate, "stateid", "statename",userdata.stateid);
ViewBag.cityid = new SelectList(allcity, "cityid", "cityname",userdata.cityid);
if (ModelState.IsValid)
{
using(nyalkaranEntities db= new nyalkaranEntities())
{
db.n_userdata.Add(userdata);
db.SaveChanges();
ModelState.Clear();
userdata = null;
ViewBag.messagee="sabmit sussesfully done";
}
}
else
{
ViewBag.messagee = "falid please try agen leter";
}
return View();
}
[HttpGet]
public JsonResult
getstate(string countryid = "")
{
List<n_state> allstate = new List<n_state>();
int id = 0;
if(int.TryParse(countryid, out id))
{
using (nyalkaranEntities db = new nyalkaranEntities())
{
allstate = db.n_state.Where(a => a.countryid.Equals(id)).OrderBy(a => a.state).ToList();
}
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = allstate,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
return new JsonResult
{
Data = "no velid rqvest",
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
}
this is my view and jqurey
@Html.DropDownListFor(model => model.CountryID,@ViewBag.countryid as SelectList,"select country")
@Html.ValidationMessageFor(model => model.CountryID)
@Html.LabelFor(model => model.StateID)
@Html.DropDownListFor(model => model.StateID, @ViewBag.stateid as SelectList,"select state")
@Html.ValidationMessageFor(model => model.StateID)
<input type="submit" value="Create" />
}
@Html.ActionLink("Back to List", "Index")
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
// this is call wen country ddl is change
$("#CountryID").change(function () {
var countryid = parseInt($("#CountryID").val());
if (!NaN(countryid)) {
var ddstate = $("#StateID");
ddstate.empty();
ddstate.append($("<option></option>").val("").html("select state"));
$.ajax({
url:"@Url.Action("Getstates","user")",
type: "GET",
data: { countryid: countryid },
datatype: "json",
success: function (data) {
$.each(data, function (i, val) {
ddstate.append(
$("<option></option>").val(val.StateID).html(val.StateName)
);
});
},
error: function () {
alert("error!!!");
}
});
}
});
});
</script>
}
//
//the country list is fill but state list is not fill