Demo简述:使用动态生成的DropDownlist,动态更新partial view
Control 动态生成 DropdownList 的方法
public ActionResult Index()
{
var products = (from product in context.GetTable<Product>()
select product).ToList();
var categorys = (from category in context.GetTable<ProductCategory>()
select new SelectListItem
{
Text = category.Title,
Value = category.Id.ToString()
}).ToList();
List<SelectListItem> listItem = new List<SelectListItem>();
listItem.Add(new SelectListItem { Text = "Choose an option"});
listItem.AddRange(categorys);
ViewData["products"] = products;
ViewData["categorys"] = listItem;
return View();
}
public ActionResult GetProductById(string id)
{
var products = from product in context.GetTable<Product>()
select product;
if (!string.IsNullOrEmpty(id) && id != "All")
{
products = products.Where(p => p.ParentId.ToString() == id);
}
return PartialView("ProductControl1", products.ToList());
}
Index View:
<div id="loading" style="display:none;color:Red;font-weight:bolder">
Loading Data.....
</div>
<fieldset>
<span>Choose different Product</span>
<div>
@using(Ajax.BeginForm
("GetProductById",
new AjaxOptions
{
UpdateTargetId = "productList",
Confirm = "Do you submit the request?",
LoadingElementId = "loading",
LoadingElementDuration = 2000
}
)
)
{
@Html.DropDownListFor(model => Model.Id,ViewData["categorys"] as List<SelectListItem>)
<input type="submit" value="Submit" />
}
</div>
</fieldset>
<div id="productList">
@{Html.RenderPartial("ProductControl1",ViewData["products"]);}
</div>
PartialView
@model IEnumerable<MvcApp.Product>
<table>
<tr>
<td>Title</td>
<td>Price</td>
<td>CreateTime</td>
</tr>
@foreach(var p in Model)
{
<tr>
<td>@p.Title</td>
<td>@p.Price</td>
<td>@p.CreateTime</td>
</tr>
}
</table>