Asp.net MVC中傳遞ViewData資料不能正確傳遞的問題
阿新 • • 發佈:2019-01-29
再次經歷MVC中兩個DropDownList中一個通過ViewData或ViewBag傳遞資料自動選擇出現問題的情況,也就是資料沒有被正確傳遞,debug 了4 hours,媽的,怎麼除錯怎麼沒有錯誤,把資料通過json顯示也沒有錯,但是就是在partialView中就是不能夠顯示正確,再一次陷入了漩渦,媽的。
忽然間想起來前面出現過類似的問題,當時把DropDownList的ID值和繫結的ViewData中的關鍵字修改成不同就可以了,因此就做了如下修改,果然ok,無語了,再次做了記錄,希望能夠對我和對大家加強印象。
例如:
Html.DropDownList("Customer_id4PoItemWithRow", ViewData[
<div id="CollectionInRow"> @Html.DropDownList("Collections",ViewData["CollectionInRow"] as IEnumerable<SelectListItem>, "--Select One--") @Html.ValidationMessage("Collections", "", new { @class = "text-danger" }) </div> <div id="SKUDiv"> @Html.DropDownList("Customer_id4PoItemWithRow", ViewData["skuselect"] as IEnumerable<SelectListItem>, "--Select One--") @Html.ValidationMessage("Customer_id4PoItemWithRow", "", new { @class = "text-danger" }) </div>
public ActionResult ShowProduct4RowByProductID(Product model) { string productId = Request.QueryString["Product_id"]; int productID = Int32.Parse(productId); model = db.Products.Find(productID); string customerType_ID = Request.QueryString["CustomerType_id"]; int cID = Int32.Parse(customerType_ID); List<SelectListItem> item = new List<SelectListItem>(); int collectionID = -1; foreach (var it in db.Products.Where(x => x.Customer_id == cID)) { Sku sku=db.Skus.Find(it.SKU); string skuName = sku.name; //collectionID = db.Skus.Find(it.SKU).collectionID; if (sku.ID==productID) collectionID = sku.collectionID; item.Add(new SelectListItem { Text = skuName, Value = sku.ID.ToString(), Selected = (it.ID == productID) }); } List<SelectListItem> tmpCol = new List<SelectListItem>(); foreach (var it in db.Collections) { tmpCol.Add(new SelectListItem { Text = it.Name, Value = it.ID.ToString(), Selected = ((collectionID == it.ID)) }); } ViewData["CollectionInRow"] = tmpCol; ViewData["skuselect"] = item; //return Json(ViewData["CollectionInRow"], JsonRequestBehavior.AllowGet); return PartialView("_product4rowByid",model); }