0
我在控制器中使用Viewbag.typeofchange
將列表傳遞給視圖。在創建網頁/視圖中,如果選擇了dropdownlist
項目,它將被正確保存到實體模型/數據庫中。如何維護DropDownList變量的原始值?
但是,在編輯網頁/視圖中,下拉列表顯示原始值,但當頁面被保存時,如果未選擇dropdownlist中的新項目,則該值會丟失。
在編輯視圖中,如果選擇dropdownlist
,則新值將存儲到數據庫中。
如何保持dropdownlist
變量typeofchange
的原始值,以便在用戶不選擇項目時不會丟失?
代碼控制器:
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Red", Value = "Red" });
items.Add(new SelectListItem { Text = "Green", Value = "Green" });
items.Add(new SelectListItem { Text = "Blue", Value = "Blue" });
items.Add(new SelectListItem { Text = "Other/Explain", Value = "Other" });
ViewBag.typeofchange = items;
代碼在編輯觀點:
<div class="editor-field">
@Html.DropDownList("typeofchange", Model.typeofchange)
</div>
代碼在實體CodeFirst型號:
[DisplayName("Type of Change")]
public string typeofchange { get; set; }
我真的很感激的反饋。
從控制器中,您將它設置在ViewBag上。在視圖中,您正在使用模型。哪一個是錯的? – 2012-07-24 03:20:09
謝謝你的回覆,我會開始研究這個。基本上,我使用Model.typeofchange值來顯示模型中的當前值,我想我必須從模型變量中設置控制器中Viewbag中的默認值。 – user1547361 2012-07-24 03:36:27
您需要一個列表來創建下拉列表,並使用模型來設置選定的值。你們都有,只是在視圖上正確使用它們。 – 2012-07-24 03:40:29