我正在使用MVC,C#和实体框架。 在我的模型中的对象是:MVC使用动态下拉列表编辑表格 - 如何设置初始值
国家 -------- ID,姓名
市 ------- ID,姓名,STATEID
TheObject ----编号,名称,StateId,CityId
我想为TheObject创建编辑表单。 “编辑”窗体具有2个动态创建的下拉列表状态和城市,城市列表取决于在状态列表上进行的选择。 问题是下拉列表填写正确,但是当编辑窗体打开时,这2个下拉列表处于空状态,并且没有为编辑的对象选择实际值。
编辑视图的部分码是这样的:
<div class="form-group">
@Html.LabelFor(u => u.State, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(u => u.State,
new SelectList(ViewBag.State, "Id", "Name"),
"Choose State",
new { @class = "form-control", @onchange = "selectCities()" })
@Html.ValidationMessageFor(u => u.State, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(u => u.City, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(u => u.City,
new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Name"),
"Choose City",
new { @class = "form-control" })
@Html.ValidationMessageFor(u => u.City, "", new { @class = "text-danger" })
</div>
</div>
function selectCities() {
debugger;
var stateId = $("#State").val();
$.ajax({
url: '/Home/selectCities',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ stateId: +stateId }),
success: function (result) {
$("#City").html("");
$("#City").append
($('<option></option>').val(null).html("---choose City---"));
$.each($.parseJSON(result), function (i, cty)
{ $("#City").append($('<option></option>').val(cty.Id).html(cty.Name)) })
},
error: function() { alert("Error !") },
});
}
控制器的部分码是这样的:
private void Fill_StateDropDownList()
{
var st = from d in db.States
orderby d.Name
select d;
ViewBag.State = st.ToList();
}
[HttpPost]
public ActionResult selectCities(string stId)
{
List <City> lstcity = new List <City>();
int stateiD = Convert.ToInt32(stId);
lstgrupet = (from d in db.Citys
where d.StateID==stateiD
select d).ToList();
string result= JsonConvert.SerializeObject(lstgrupet, Formatting.Indented,
new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
return Json(result, JsonRequestBehavior.AllowGet);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TheObject obj = db.TheObjects.Find(id);
if (obj == null)
{
return HttpNotFound();
}
Fill_StateDropDownList()
return View(obj);
}
[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult EditPost(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var theobjectToUpdate = db.TheObjects.Find(id);
if (TryUpdateModel(theobjectToUpdate, "",
new string[] { "Name","StateId","CityId" }))
{
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception)
{
ModelState.AddModelError("", "Error.");
}
}
Fill_StateDropDownList()
return View(theobjectToUpdate);
}
不起作用,州和城市的dropdownlists仍处于空状态,所以当前编辑对象的值没有被选中。 – Adriano
@Adriano - 您必须使用所选值填充u.State。 –
@Erik你能告诉我,我该怎么做? – Adriano