MVC3 使用動態生成的DropDownList,更新partial view

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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章