Asp.net-Mvc

DefaultModelBinder 不綁定嵌套模型

  • November 29, 2017

看起來其他人遇到了這個問題,但我似乎找不到解決方案。

我有 2 個模型:Person 和 BillingInfo:

public class Person
{
public string Name { get; set;}
public BillingInfo BillingInfo { get; set; }
}

public class BillingInfo
{
public string BillingName { get; set; }
}

我正在嘗試使用 DefaultModelBinder 將其直接綁定到我的 Action 中。

public ActionResult DoStuff(Person model)
{
// do stuff
}

但是,在設置 Person.Name 屬性時,BillingInfo 始終為空。

我的文章是這樣的:

“名稱=statichippo&BillingInfo.BillingName=statichippo”

為什麼 BillingInfo 總是為空?

狀態沒有複製。您的問題出在其他地方,無法確定您提供的資訊來自何處。預設模型綁定器與嵌套類完美配合。我已經用了無數次了,而且一直有效。

模型:

public class Person
{
   public string Name { get; set; }
   public BillingInfo BillingInfo { get; set; }
}

public class BillingInfo
{
   public string BillingName { get; set; }
}

控制器:

[HandleError]
public class HomeController : Controller
{
   public ActionResult Index()
   {
       var model = new Person
       {
           Name = "statichippo",
           BillingInfo = new BillingInfo
           {
               BillingName = "statichippo"
           }
       };
       return View(model);
   }

   [HttpPost]
   public ActionResult Index(Person model)
   {
       return View(model);
   }
}

看法:

<% using (Html.BeginForm()) { %>
   Name: <%: Html.EditorFor(x => x.Name) %>
   <br/>
   BillingName: <%: Html.EditorFor(x => x.BillingInfo.BillingName) %>
   <input type="submit" value="OK" />
<% } %>

Posted values:Name=statichippo&BillingInfo.BillingName=statichippo完全綁定在 POST 動作中。同樣適用於 GET。


這可能不起作用的一種可能情況如下:

public ActionResult Index(Person billingInfo)
{
   return View();
}

注意 action 參數是如何被呼叫的billingInfo,與屬性同名BillingInfo。確保這不是你的情況。

我遇到了這個問題,答案盯著我看了幾個小時。我將它包括在這裡是因為我正在尋找沒有綁定的嵌套模型並得出了這個答案。

確保您的嵌套模型的屬性,就像您希望綁定工作的任何模型一樣,具有正確的訪問器。

   // Will not bind!
   public string Address1;
   public string Address2;
   public string Address3;
   public string Address4;
   public string Address5;


   // Will bind
   public string Address1 { get; set; }
   public string Address2 { get; set; }
   public string Address3 { get; set; }
   public string Address4 { get; set; }
   public string Address5 { get; set; }

引用自:https://stackoverflow.com/questions/3928120