页面JS代码
<script type="text/javascript">
function GetTypeByParentID(id) {
$("#ChildType").empty();
$("#ChildType").children().remove();
$.ajax({
url: '/Entry/GetSecondType/' + $(id).val(),
type: "get",
datatype: "json",
success: function (data) {
$.each(data, function (i, item) {
$("<input id="TypeId" type="radio"name="TypeId">" + item["Name"] + "</input>")
.val(item["Id"])
.appendTo($("#ChildType"));
});
}
});
}
</script>
Controller里的代码
[HttpGet]
public ActionResult Form(int? id)
{
QueryType();
EntryModel model = new EntryModel();
if (id != null)
{
model = business.Get(id.Value);
}
return View(model);
}
private void QueryType()
{
EntryTypeRepository rep = new EntryTypeRepository();
var list = rep.QueryByParentId(0);
var select = new List<SelectListItem>();
foreach (var item in list)
{
select.Add(new SelectListItem() { Text=item.Name,Value = item.Id.ToString()});
}
ViewBag.TypeList = select;
}
public ActionResult GetSecondType(int id = 0)
{
var list = new List<EntryTypeModel>();
if (id != 0)
{
EntryTypeRepository rep = new EntryTypeRepository();
list = rep.QueryByParentId(id);
}
else{
list = new List<EntryTypeModel>();
}
return Json(list, JsonRequestBehavior.AllowGet);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Form(EntryModel model)
{
if (ModelState.IsValid)
{
if (model.Id == 0)
{
business.Add(model);
}
else
{
business.Update(model.Id,model);
}
ViewBag.Msg = "添加成功!";
ViewBag.ReturnUrl = "/Entry/List";
QueryType();
}
return View();
}