在這個項目中,我們有兩個名單,一個是經銷商,另一個是他的產品。如何動態創建複選框或多選MVC 4
到目前爲止,如果你檢查一個經銷商,我們會回來這個特定經銷商的所有產品,它在JavaScript(Json)中實現。
HTML(5 :)
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>DealerProduct</legend>
<div class="editor-label">
@Html.LabelFor(model => model.DealerID)
</div>
<div class="editor-field">
@Html.DropDownList("DealerID", String.Empty)
@Html.ValidationMessageFor(model => model.DealerID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProductID)
</div>
<div class="editor-field">
@Html.DropDownList("ProductID", String.Empty)
@Html.ValidationMessageFor(model => model.ProductID)
</div>
<p>
<input type="submit" value="@Shared.Add" />
</p>
</fieldset>
}
的JavaScript(JSON :)
<script type="text/javascript">
$(document).ready(function()
{
$("#DealerID").change(function()
{
var self = $(this);
var items="";
var url = "";
url = "@Url.Action("GetDealerProducts","DealerProduct")/"+self.val();
$.ajaxSetup({ cache: false });
$.getJSON(url,function(data)
{
$.each(data,function(index,item)
{
items+="<option value='"+item.Value+"'>"+item.Text+"</option>\n";
});
$("#ProductID").html(items);
$.ajaxSetup({ cache: true });
});
});
});
</script>
控制器:
public ActionResult GetDealerProducts(int id)
{
Dealer currentDealer = db.Dealers.Single(p => p.UserName == User.Identity.Name);
Dealer subDealer = db.Dealers.Single(s => s.DealerID == id);
List<Product> productOpenToSale = new List<Product>();
foreach (var item in currentDealer.ProductToSale)
if (!subDealer.ProductToSale.ToList().Exists(e => e.ProductID == item.ProductID))
productOpenToSale.Add(item.Product);
List<SelectListItem> productOpenToSaleList = new List<SelectListItem>();
productOpenToSale.ForEach(item => productOpenToSaleList.Add(new SelectListItem { Value = item.ProductID.ToString(), Text = item.ProductName }));
return Json(productOpenToSaleList, JsonRequestBehavior.AllowGet);
}
我真正需要的是增加(的配對)產品經銷商,他可以在未來銷售。
目前的選擇是逐個添加產品,希望給出所有產品的多重選擇的可能性。
也許類似於動態checkBoxList或來自ViewModel的添加輸入的列表中的foreach - 複選框like this,但我不知道如何在經銷商選擇第一個列表並接收所有選定的產品後填充它回提交..
10X任何幫助! (& &對不起我的英語不好:)
不錯,但.. =)我需要從DropDownList(「DealerID」 – oCcSking
使用ajax選擇一個經銷商後,在這個SelectedItemIds填充不同的產品只是帶來的價值,你想要的鍵值pare,並追加或插入到SelectedItemIds就像你在 – 1AmirJalali
以上所做的那樣很好地工作了10x alot =)) – oCcSking