MVC使用动态下拉列表编辑表格 - 如何设置初始值
我正在使用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);
}
实际上SelectList
具有与被叫参数的构建selectedValue
现在你应该知道如何去做
in编辑查看
<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", Model.State),
"Choose State",
new { @class = "form-control", @onchange = "selectCities()" })
@Html.ValidationMessageFor(u => u.State, "", new { @class = "text-danger" })
</div>
</div>
您已拥有保存的状态和城市值。您所要做的就是根据保存的状态ID加载城市的子集,并使用该集合呈现城市的下拉菜单
DropDownListFor
帮助程序方法将从SELECT元素中选择相应的选项,只要视图模型的City属性值与选项的值属性值之一相匹配。
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TheObject obj = db.TheObjects.Find(id);
if (user == null)
{
return HttpNotFound();
}
Fill_StateDropDownList()
FillCities(obj.State);
return View(obj);
}
private void FillCities(int stateId)
{
ViewBag.CityList = db.Cities
.Where(g => g.StateId== stateId)
.Select(f => new SelectListItem() {
Value = f.Id.ToString(),
Text = f.Name })
.ToList();
}
进行调整的观点
var cityList = new List<SelectListItem>();
if (ViewBag.CityList != null)
{
cityList =ViewBag.CityList as List<SelectListItem>;
}
@Html.DropDownListFor(u => u.City, cityList , "Choose City")
另一种选择是,就在页面加载Ajax调用(文档准备基于状态下拉列表的值来获得城市)。如果你有多个嵌套下拉列表,它会变得复杂(最后在回调地狱中)
注释不适用于扩展讨论或调试会话;这个对话已经[转移到聊天](http://chat.stackoverflow.com/rooms/155188/discussion-on-answer-by-shyju-mvc-edit-form-with-dynamic-dropdown-list-how-至)。请确保将来自聊天的相关信息酌情并入问题或答案中。 –
不起作用,州和城市的dropdownlists仍处于空状态,所以当前编辑对象的值没有被选中。 – Adriano
@Adriano - 您必须使用所选值填充u.State。 –
@Erik你能告诉我,我该怎么做? – Adriano