簡體   English   中英

@ Html.DropDownList提交時返回null

[英]@Html.DropDownList returns null when submitted

我這里有一個場景。 我想在表單中執行HTTP POST操作,所以這是我的操作方法。

public class Item
{
  public Item()
  {
    Storages = new HashSet<Storage>();
  }
  public int Id { get; set; }
  public string Name { get; set; }

  public virtual ICollection<Storage> Storages { get; set; }
  -- remove some lines for brevity --
}

public class Storage
{
  public int Id { get; set; }
  public string Name { get; set; }
  --- remove some lines for brevity --
}

因此,基本上,一個Item具有許多Storage ,因此我創建了視圖模型。

public class CreateStockViewModel
{
  public string Name { get; set; }
  public int StorageId { get; set; }
  -- remove some lines for brevity --
}

在我的Controller 我有這個

[HttpGet]
public ActionResult Create()
{
  ViewBag.Storages = _storageService.All
                       .OrderBy(i => i.Name)
                       .ToSelectList(s => s.Name, s => s.Id);

  return View();
}

在我看來:

@model Wsfis.Web.ViewModels.ItemViewModels.CreateStockViewModel

@Html.DropDownList("Storages")

現在我的問題是,當我提交表格時。 並對正在傳遞的模型進行Quick Watch Null0

public ActionResult Create(CreateStockViewModel item)
{
  // some code
}

簡而言之,

  1. 當我提交表單時,除了@Html.DropDownList之外,所有其他字段都將被綁定。 我在哪里錯過了?

一些補充說明:

  1. 他們說Views應該是強類型的。 那我該在View傳遞什么呢? (示例代碼會很棒。謝謝)

至於ToSelectList方法,我復制了這段代碼 (希望它可以)

任何幫助將非常感激。 謝謝。

表單輸入的屬性名稱不同,因此默認的模型綁定器不知道如何綁定模型。

您可以將其他名稱傳遞給DropDownList幫助器,但是我更喜歡使用強類型的幫助器:

@Html.DropDownListFor(m => m.StorageId, ViewBag.Storages as IEnumerable<SelectListItem>)

嘗試這樣:

 ViewBag.StorageId = _storageService.All
                       .OrderBy(i => i.Name)
                       .ToSelectList(s => s.Name, s => s.Id);

鑒於:

@Html.DropDownList("StorageId")

現在它將在CreateStockViewModel對象的StorageId屬性中發布下拉列表選擇的值。

暫無
暫無

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

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