您的位置:首页 > 其它

简单的MVC实现层叠的Ajax下拉

2011-09-22 09:52 302 查看
项目已经接近尾声了,回顾下之前项目整体实现,运用到技术,总结下。

界面主要以MVC2+jquery来实现,数据存储主要以接口wcf来进行数据传输。整体来看界面中大量运用到jquery,看着那一堆堆js,不知有何冲动,因为之前也接触过3的一些新特性及其有了一点了解,于是写了一个ajax层叠下拉效果,代码很清晰:

1,首先先定义导入jquery库和css,在这里我定义一个_Layout.cshtml页面

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
</head>
<body>
@RenderBody()

</body>
</html>


2,再定义一个cshtml页面,用于显示,并把之前定义的页面导入该页面

@model MvcApplication1.Models.ProductCatalog
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table cellpadding="0" cellspacing="4" border="0">
<tr>
<td>第一级 </td>
<td> :</td>
<td>@Html.Partial("CategoriesUserControl", Model)</td>
</tr>
<tr>
<td>第二级 </td>
<td> :</td>
<td><div id="SubCategories">@Html.Partial("SubCategoriesUserControl", Model)</div></td>
</tr>
<tr>
<td>第三级 </td>
<td> :</td>
<td><div id="Products">@Html.Partial("ProductsUserControl", Model)</div></td>
</tr>
</table>

3,接下来定义controller

[HttpPost]
public ActionResult SelectCategory(int? selectedCategoryId)
{
ProductCatalog productCatalog = new ProductCatalog();
productCatalog.SubCategories = new List<SubCategory>();

if (selectedCategoryId.HasValue)
{
productCatalog.SubCategories = (from s in ProductCatalog.GetSubCategories()
where s.CategoryId == selectedCategoryId
orderby s.Name
select s).ToList();
}

return PartialView("SubCategoriesUserControl", productCatalog);

}


这里是一post方式提交.最终返回一个视图页面:第一个下拉返回SubCategoriesUserControl.cshtml页面,然后再SubCategoriesUserControl页面上定义

@model MvcApplication1.Models.ProductCatalog
@if (Model.SubCategories != null && Model.SubCategories.Count() > 0)
{
using (Ajax.BeginForm("SelectSubCategory", "CascadingDropDown", new AjaxOptions { UpdateTargetId = "Products" }))
{
@Html.HiddenFor(m => m.SelectedCategoryId)
@Html.DropDownListFor(
m => m.SelectedSubCategoryId,
new SelectList(Model.SubCategories, "Id", "Name"),
string.Empty
)
}
}
<script type="text/javascript">
$('#SelectedSubCategoryId').change(function () {
$(this).parents('form').submit();
});
</script>

这里用change事件触发下拉,以post方式提交页面数据。这种方式很清楚,也是当成了自定义控件方式来进行调用。第二级的层叠下拉和第一级一样。

代码就不贴上了,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐