Я пытался три дня, но я не мог понять ошибки, потому что код правильный, но его реализация не то, что я хочу. Я использую три таблицы State, City и Donator, и я хочу, чтобы donator выбирал его штат и город, при выборе штата отображал указанный город, но при сохранении его информации cityId не сохранялся, как на изображении, как в конце.
Сначала я использую код. net mvc 5.
любой может помочь и подсказать мне, как решить эту проблему, следуя моим Моделям, Контроллеру и Представлению:
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);
}
}
// Создать представление
@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>
представление создания донатора:
после сохранения информации о доноре (индекс просмотр)