Javascript 带有ajax生成的选项的下拉列表,不保存CityId属性
我已经尝试了三天,但我无法找出错误,因为代码是正确的,但它的实现不是我想要的。 我使用的是三个表格State、City和Donator,我希望Donator在选择State时选择它的State和City,它显示指定的城市,但在保存其信息时,cityId不会在最后的图像中另存为 我首先使用ap.NETMVC5代码 任何人都可以帮助我,告诉我如何解决这个问题 以下是我的模型、控制器和视图:Javascript 带有ajax生成的选项的下拉列表,不保存CityId属性,javascript,c#,html,asp.net-mvc,Javascript,C#,Html,Asp.net Mvc,我已经尝试了三天,但我无法找出错误,因为代码是正确的,但它的实现不是我想要的。 我使用的是三个表格State、City和Donator,我希望Donator在选择State时选择它的State和City,它显示指定的城市,但在保存其信息时,cityId不会在最后的图像中另存为 我首先使用ap.NETMVC5代码 任何人都可以帮助我,告诉我如何解决这个问题 以下是我的模型、控制器和视图: public enum Gender { Male, Femal } public class
public enum Gender
{ Male, Femal }
public class Donator
{
public int Id { get; set; }
public string Name { get; set; }
public Gender gender { get; set; }
public int Age { get; set; }
public string BloodType { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
[ForeignKey("StateId")]
public State state { get; set; }
}
//State Table
public class State
{
public int StateId { get; set; }
public string StateName { get; set; }
public ICollection<City> cities { get; set; }
public ICollection<Donator> donS { get; set; }
}
//City table
public class City
{
public int CityId { get; set; }
public string CityName { get; set; }
public int StateId { get; set; }
[ForeignKey("StateId")]
public State state { get; set; }
}
//Donators Controller
public class DonatorsController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Donators
public ActionResult Index()
{
return View(db.Donators.ToList());
}
// GET: Donators/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Donator donator = db.Donators.Find(id);
if (donator == null)
{
return HttpNotFound();
}
return View(donator);
}
// GET: Donators/Create
public ActionResult Create()
{
ViewBag.StateId = new SelectList(db.state, "StateId", "StateName");
return View();
}
// POST: Donators/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,gender,Age,BloodType,CountryId,StateId")] Donator donator)
{
if (ModelState.IsValid)
{
db.Donators.Add(donator);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.StateId = new SelectList(db.state, "StateId", "StateName", donator.StateId);
return View(donator);
}
// GET: Donators/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Donator donator = db.Donators.Find(id);
if (donator == null)
{
return HttpNotFound();
}
ViewBag.StateId = new SelectList(db.state, "StateId", "StateName", donator.StateId);
return View(donator);
}
// POST: Donators/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,gender,Age,BloodType,StateId,CityId")] Donator donator)
{
if (ModelState.IsValid)
{
db.Entry(donator).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CountryId = new SelectList(db.country, "CountryId", "CountryName");
return View(donator);
}
// GET: Donators/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Donator donator = db.Donators.Find(id);
if (donator == null)
{
return HttpNotFound();
}
return View(donator);
}
// POST: Donators/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Donator donator = db.Donators.Find(id);
db.Donators.Remove(donator);
db.SaveChanges();
return RedirectToAction("Index");
}
public JsonResult StateList(int Id)
{
var state = from s in db.state
where s.CountryId == Id
select s;
return Json(new SelectList(state.ToArray(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);
}
public JsonResult Citylist(int id)
{
var city = from c in db.city
where c.StateId == id
select c;
return Json(new SelectList(city.ToArray(), "CityId", "CityName"), JsonRequestBehavior.AllowGet);
}
public IList<State> Getstate(int CountryId)
{
return db.state.Where(m => m.CountryId == CountryId).ToList();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadClassesByCountryId(string CountryName)
{
var stateList = this.Getstate(Convert.ToInt32(CountryName));
var stateData = stateList.Select(m => new SelectListItem()
{
Text = m.StateName,
Value = m.CountryId.ToString(),
});
return Json(stateData, JsonRequestBehavior.AllowGet);
}
公共枚举性别
{男,女}
公共类捐赠者
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共性别{get;set;}
公共整数{get;set;}
公共字符串BloodType{get;set;}
public int StateId{get;set;}
public int CityId{get;set;}
[外国密钥(“国家ID”)]
公共状态状态{get;set;}
}
//状态表
公共阶级国家
{
public int StateId{get;set;}
公共字符串StateName{get;set;}
公共i集合城市{get;set;}
公共ICollection donS{get;set;}
}
//城市表
公营城市
{
public int CityId{get;set;}
公共字符串CityName{get;set;}
public int StateId{get;set;}
[外国密钥(“国家ID”)]
公共状态状态{get;set;}
}
//捐赠者控制器
公共类捐赠者控制器:控制器
{
私有ApplicationDbContext db=新ApplicationDbContext();
//获得:捐赠者
公共行动结果索引()
{
返回视图(db.Donators.ToList());
}
//获取:捐赠者/详细信息/5
公共行动结果详细信息(int?id)
{
if(id==null)
{
返回新的HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Donator Donator=db.Donators.Find(id);
如果(施主==null)
{
返回HttpNotFound();
}
返回视图(供体);
}
//获取:捐赠者/创建
公共操作结果创建()
{
ViewBag.StateId=新选择列表(db.state,“StateId”,“StateName”);
返回视图();
}
//帖子:捐赠者/创建
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include=“Id,Name,gender,Age,BloodType,CountryId,StateId”)]Donator-Donator)
{
if(ModelState.IsValid)
{
db.Donators.Add(donator);
db.SaveChanges();
返回操作(“索引”);
}
ViewBag.StateId=新选择列表(db.state,“StateId”,“StateName”,donator.StateId);
返回视图(供体);
}
//获取:捐赠者/编辑/5
公共行动结果编辑(int?id)
{
if(id==null)
{
返回新的HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Donator Donator=db.Donators.Find(id);
如果(施主==null)
{
返回HttpNotFound();
}
ViewBag.StateId=新选择列表(db.state,“StateId”,“StateName”,donator.StateId);
返回视图(供体);
}
//职位:捐赠者/编辑/5
[HttpPost]
[ValidateAntiForgeryToken]
公共行动结果编辑([Bind(Include=“Id,Name,gender,Age,BloodType,StateId,CityId”)]Donator-Donator)
{
if(ModelState.IsValid)
{
db.Entry(donator.State=EntityState.Modified;
db.SaveChanges();
返回操作(“索引”);
}
ViewBag.CountryId=新的选择列表(db.country,“CountryId”,“CountryName”);
返回视图(供体);
}
//获取:捐赠者/删除/5
公共操作结果删除(int?id)
{
if(id==null)
{
返回新的HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Donator Donator=db.Donators.Find(id);
如果(施主==null)
{
返回HttpNotFound();
}
返回视图(供体);
}
//帖子:捐赠者/删除/5
[HttpPost,ActionName(“删除”)]
[ValidateAntiForgeryToken]
公共行动结果删除已确认(内部id)
{
Donator Donator=db.Donators.Find(id);
db.Donators.Remove(donator);
db.SaveChanges();
返回操作(“索引”);
}
公共JsonResult状态列表(int Id)
{
var state=从处于db.state的s开始
其中s.CountryId==Id
选择s;
返回Json(新的SelectList(state.ToArray(),“StateId”,“StateName”),JsonRequestBehavior.AllowGet);
}
公共JsonResult城市列表(int id)
{
var city=从c到db city
其中c.StateId==id
选择c;
返回Json(新的SelectList(city.ToArray(),“CityId”,“CityName”),JsonRequestBehavior.AllowGet);
}
公共IList Getstate(国际国家ID)
{
返回db.state.Where(m=>m.CountryId==CountryId.ToList();
}
[接受动词(HttpVerbs.Get)]
public JsonResult LoadClassesByCountryId(字符串CountryName)
{
var stateList=this.Getstate(Convert.ToInt32(CountryName));
var stateData=stateList.Select(m=>newselectListItem()
{
Text=m.StateName,
Value=m.CountryId.ToString(),
});
返回Json(stateData,JsonRequestBehavior.AllowGet);
}
}
//创建视图
@model WebApplication6.Models.Donator
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
<script type="text/jscript">
$(function () {
$('#State').change(function () {
$.getJSON('/Donators/Citylist/' + $('#State').val(), function (data) {
var items = '<option>Select a City</option>';
$.each(data, function (i, city) {
items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
});
$('#city').html(items);
});
});
});
</script>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Donator</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.gender, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EnumDropDownListFor(model => model.gender, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.gender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.BloodType, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.BloodType, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.BloodType, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.StateId, "StateId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("StateId", null, htmlAttributes: new {id="State", @class = "form-control" })
@Html.ValidationMessageFor(model => model.StateId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CityId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("City", new SelectList(string.Empty, "Value", "Text"), htmlAttributes: new { id = "city", @class = "form-control" })
@Html.ValidationMessageFor(model => model.CityId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
@model WebApplication6.Models.Donator
@{
Layout=“~/Views/Shared/_Layout.cshtml”;
}
创造
@Scripts.Render(“~/bundles/jquery”)
@Scripts.Render(“~/bundles/jqueryval”)
$(函数(){
$('#State')。更改(函数(){
$.getJSON('/Donators/Citylist/'+$('#State').val(),函数(数据){
变量项='选择一个城市';
$。每个(数据、功能(i、城市){
项目+=“”+城市。文本+“”;
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,gender,Age,BloodType,CountryId,StateId,CityId")] Donator donator)
{
// add cityId to the bind parameters above
...
}
// please update first string parameter to CityId
@Html.DropDownList("CityId", new SelectList(string.Empty, "Value", "Text"), htmlAttributes: new { id = "city", @class = "form-control" })