簡體   English   中英

ASP.NET @Html.DropDownListFor() 選擇值設置為 true 但提交到 controller 時返回 false

[英]ASP.NET @Html.DropDownListFor() selected value is set to true but returns false when submitted to the controller

當我提交代碼時,我不知道發生了什么。 我正在嘗試根據提交時選擇的內容來獲取員工和經銷商@Html.DropDownListFor()的正確值。 我在 controller 的[HttpGet]方法中將值設置為 true,並且在傳遞給視圖時設置並正確顯示。但是當我提交表單時,我在 controller 的[HttpPost]方法中變得false 這是 controller,查看,查看模型代碼。

Controller

      [HttpGet]
      public ActionResult CreateNewItem() {

            CreateNewItemViewModel viewModel = new CreateNewItemViewModel()
            {
               EnableListingEmployee = true, 
               EnableListingDealer = true,
               ...
            };
            return View(viewModel);
      }

      [HttpPost]
      public ActionResult CreateNewItem(CreateNewItemViewModelviewModel viewModel) {
        ...
      }

看法

   <!-- Employee Enable Listing -->
   <tr class="optionYes">
     <td class="DisplayFieldName">
       @Html.LabelFor(m => m.EnableListingEmployee)
     </td>
     <td class="DisplayFieldData">
       @Html.DropDownListFor(m => m.EnableListingEmployee, new[] 
                            { new SelectListItem { Text = "Yes", Value = "true" },
                              new SelectListItem {Text = "No", Value = "false" } },"Select.....",
                              new { @Name = "EmployeeEnableListing", @id = "EmployeeEnableListing", style = "width:207px;font-size:10pt;" })                            
      </td>
   </tr>

Dealer 只是 Dealer 在 Employee 的地方。

視圖模型

[Display(Name = "Enable Listing")]
public bool EnableListingEmployee { get; set; }

我認為這就是一切,如果我們需要看其他內容,請告訴我。

這是因為以下代碼:

 new { @Name = "EmployeeEnableListing"

由於您更改了下拉列表的名稱屬性,因此在發布表單時,mvc model 活頁夾無法填充EnableListingEmployee屬性。 由於 mvc 將輸入元素的 name 屬性綁定到表單帖子上的 Model object 屬性。

目前它發布為false ,因為它是bool的默認值,這意味着該值實際上並未發布。

您需要刪除這個明確的名稱以使其工作。

就像是:

@Html.DropDownListFor(m => m.EnableListingEmployee, new[] 
                        { 
                          new SelectListItem { Text = "Yes", Value = "true" },
                          new SelectListItem {Text = "No", Value = "false" } 
                        },
                        "Select.....",
                        new 
                        { 
                            id = "EmployeeEnableListing", 
                            style = "width:207px;font-size:10pt;" 
                        }
                      )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM