我有一个库存创建视图,其中包含以下内容:选择项目类别> item(选择类别时由jquery填充)>建筑物>房间(在选择建筑物时填充)然后输入数量。在提交时,如果模型无效并返回到创建屏幕,则会重置所有下拉列表。我想要做的是模型无效,如果我没有选择房间,我仍然希望我的选择类别,项目和建筑保持。也许我应该采用不同的方式来填充这些下拉列表(我以前从未这样做过,所以也许我错过了这样做的“标准”)?
InventoryViewModel
public class InventoryViewModel
{
public IList<SelectListItem> BuildingNames { get; set; }
public IList<SelectListItem> RoomNames { get; set; }
public IList<SelectListItem> CategoryNames { get; set; }
public IList<SelectListItem> ItemNames { get; set; }
public int InventoryItemID { get; set; }
public virtual Item Item { get; set; }
[DisplayName("Item")]
[Required (ErrorMessage="You must select an item.")]
[Range(1, Int32.MaxValue, ErrorMessage="You must select an item.")]
public int ItemID { get; set; }
public virtual Room Room { get; set; }
[DisplayName("Room")]
[Required(ErrorMessage = "You must select a storage room.")]
[Range(1, Int32.MaxValue, ErrorMessage="You must select a room.")]
public int RoomID { get; set; }
[Range(1, Int32.MaxValue, ErrorMessage = "You must enter a quantity greater than 0.")]
[Required(ErrorMessage = "You must enter a quantity.")]
public int Qty { get; set; }
public DateTime UpdateDT { get; set; }
public string UpdateBy { get; set; }
public DateTime CreateDT { get; set; }
public string CreateBy { get; set; }
}
控制器
public ActionResult Create()
{
var itm = GetCreateInventoryViewModel();
return View(itm);
}
private InventoryViewModel GetCreateInventoryViewModel()
{
List<SelectListItem> buildingNames = new List<SelectListItem>();
List<SelectListItem> categoryNames = new List<SelectListItem>();
InventoryViewModel itm = new InventoryViewModel();
List<Building> buildings = db.Buildings.ToList();
buildings.ForEach(x =>
{
buildingNames.Add(new SelectListItem { Text = x.Name, Value = x.BuildingID.ToString() });
});
itm.BuildingNames = buildingNames;
List<ItemCategory> categories = db.ItemCategories.ToList();
categories.ForEach(x =>
{
categoryNames.Add(new SelectListItem { Text = x.Name, Value = x.ItemCategoryId.ToString() });
});
itm.CategoryNames = categoryNames;
return itm;
}
[HttpPost]
public ActionResult GetRoom(string buildingId)
{
int buildId;
List<SelectListItem> roomNames = new List<SelectListItem>();
if (!string.IsNullOrEmpty(buildingId))
{
buildId = Convert.ToInt32(buildingId);
List<Room> rooms = db.Rooms.Where(x => x.BuildingID == buildId).ToList();
rooms.ForEach(x =>
{
roomNames.Add(new SelectListItem { Text = x.Name, Value = x.RoomID.ToString() });
});
}
return Json(roomNames, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult GetItem(string categoryId)
{
int catId;
List<SelectListItem> itemNames = new List<SelectListItem>();
if (!string.IsNullOrEmpty(categoryId))
{
catId = Convert.ToInt32(categoryId);
List<Item> items = db.Items.Where(x => x.ItemCategoryID == catId).ToList();
items.ForEach(x =>
{
itemNames.Add(new SelectListItem { Text = x.Name, Value = x.ItemID.ToString() });
});
}
return Json(itemNames, JsonRequestBehavior.AllowGet);
}
查看(和jquery)
@model EventsWebsite.Models.InventoryViewModel
@{
ViewBag.Title = "Create";
}
<div class="row">
<div class="col-md-8">
@Html.ActionLink("Back to List", "Index")
</div>
<div class="col-md-8">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">New Inventory Item</h3>
</div>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="box-body">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.ValidationMessage("Error", new { @class = "text-danger" })
<div class="form-group">
<label class="control-label" for="ddlCategory">Category</label>
<div>
@Html.DropDownListFor(x => x.CategoryNames, Model.CategoryNames, "---Select---", new { @id = "ddlCategory", @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ItemID, "Item", htmlAttributes: new { @class = "control-label" })
<div id="Item">
@Html.DropDownListFor(x => x.ItemNames, new List<SelectListItem>(), "---Select---", new { @id = "ItemID", @class = "form-control", @name = "ItemID" })
</div>
@Html.ValidationMessageFor(model => model.ItemID, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<label class="control-label" for="ddlBuilding">Building</label>
@Html.DropDownListFor(x => x.BuildingNames, Model.BuildingNames, "---Select---", new { @id = "ddlBuilding", @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.RoomID, "Room", htmlAttributes: new { @class = "control-label" })
<div id="Room">
@Html.DropDownListFor(x => x.RoomNames, new List<SelectListItem>(), "---Select---", new { @id = "RoomID", @class = "form-control", @name = "RoomID" })
@Html.ValidationMessageFor(model => model.RoomID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Qty, htmlAttributes: new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.Qty, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Qty, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="box-footer">
@Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
<input type="submit" value="Create" class="btn btn-primary pull-right" />
</div>
}
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#ddlBuilding').change(function () {
$.ajax({
type: "post",
url: "/Inventory/GetRoom",
data: { buildingId: $('#ddlBuilding').val() },
datatype: "json",
traditional: true,
success: function (data){
var room = "<select id='RoomID' name='RoomID' class='form-control'>";
room = room + '<option value="">--Select--</option>';
for(var i=0; i < data.length; i++)
{
room = room + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
room = room + '</select>';
$('#Room').html(room);
}
})
});
$('#ddlCategory').change(function () {
$.ajax({
type: "post",
url: "/Inventory/GetItem",
data: { categoryId: $('#ddlCategory').val() },
datatype: "json",
traditional: true,
success: function (data) {
var item = "<select id='ItemID' name='ItemID' class='form-control'>";
item = item + '<option value="">--Select--</option>';
for (var i = 0; i < data.length; i++) {
item = item + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
item = item + '</select>';
$('#Item').html(item);
}
})
});
});
</script>