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

项目已经接近尾声了,回顾下之前项目整体实现,运用到技术,总结下。
界面主要以MVC2+jquery来实现,数据存储主要以接口wcf来进行数据传输。整体来看界面中大量运用到jquery,看着那一堆堆js,不知有何冲动,因为之前也接触过3的一些新特性及其有了一点了解,于是写了一个ajax层叠下拉效果,代码很清晰:
1,首先先定义导入jquery库和css,在这里我定义一个_Layout.cshtml页面

@ViewBag.Title @RenderBody()



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

@model MvcApplication1.Models.ProductCatalog @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } 第一级   : @Html.Partial("CategoriesUserControl", Model)
第二级   : @Html.Partial("SubCategoriesUserControl", Model)
第三级   : @Html.Partial("ProductsUserControl", Model)

3,接下来定义controller
[HttpPost] public ActionResult SelectCategory(int? selectedCategoryId) { ProductCatalog productCatalog = new ProductCatalog(); productCatalog.SubCategories = new List();
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 ) } }
这里用change事件触发下拉,以post方式提交页面数据。这种方式很清楚,也是当成了自定义控件方式来进行调用。第二级的层叠下拉和第一级一样。
代码就不贴上了,
Tags:  ajax下拉框 mvcajax

延伸阅读

最新评论

发表评论