2011-04-13 59 views
1

問題:當使用EditorFor丟失數據Post對於

當我提交表單時,我失去了輸入到地址編輯模板的任何信息。

我有以下型號:

public class MoveRecord 
{ 
    public Address StartPoint { get; set; } 
    public Address EndPoint { get; set; } 
} 

所在地址被定義爲:

public class Address 
{ 
    public String City { get; set;} 
    public String State { get; set; } 
    public String Line1{ get; set; } 
    public String PostalCode { get; set; } 
} 

這裏是我的操作方法:

[HttpPost] 
public ActionResult Edit(MoveRecord model) 
{ 
    if (ModelState.IsValid) 
    { 
     //Save info 
    } 

    return View(model); 
} 

我的編輯視圖使用:

using (Html.BeginForm("Edit", "Move", FormMethod.Post)) 
{ 
    @Html.EditorFor(m => m.StartPoint); 
    @Html.EditorFor(m => m.EndPoint); 
    <input type="submit" value="Save" /> 
} 

我的編輯模板是:

<table class="form address"> 
    <tbody> 
     <tr> 
      <th style="width: 200px;"> 
       @Html.LabelFor(m => m.Line1): 
      </th> 
      <td> 
       @Html.TextBoxFor(m => m.Line1, new { style = "width: 300px;" }) 
      </td> 
     </tr> 
     <tr id="zip"> 
      <th> 
       @Html.LabelFor(m => m.PostalCode): 
      </th> 
      <td> 
       @Html.TextBoxFor(m => m.PostalCode, new { style = "width: 150px;" }) 
      </td> 
     </tr> 
     <tr id="city"> 
      <th> 
       @Html.LabelFor(m => m.City): 
      </th> 
      <td> 
       @Html.TextBoxFor(m => m.City, new { style = "width: 150px;" }) 
      </td> 
     </tr> 
     <tr id="state"> 
      <th> 
       @Html.LabelFor(m => m.StateProvince): 
      </th> 
      <td> 
       @Html.TextBoxFor(m => m.StateProvince, new { style = "width: 150px;" }) 
      </td> 
     </tr> 
    </tbody> 
</table> 

一切都渲染得很好,但是當我提交表單,我在操作方法不包含輸入到地址字段中的任何信息獲取模式。如果我將所有內容都移動到相同的視圖中,那麼它的工作原理很好,但我希望能夠使用編輯器模板來保持我的視圖易於閱讀。 如何從編輯器模板中正確綁定到模型的數據?

編輯:發佈我的操作方法

+0

你的Action方法簽名是什麼樣子的? – 2011-04-13 19:33:57

+0

我將我的操作方法添加到了我原來的問題 – 2011-04-13 19:49:06

回答

0

動作要提交的形式必須是這樣的:

[HttpPost] 
public ActionResult Edit(MoveRecord model) 
{ 
    // model.StartPoint and model.EndPoint should be correctly bound here. 
    ... 
} 

或者,如果你想直接綁定兩個地址,你需要設置正確的前綴:

[HttpPost] 
public ActionResult Edit(
    [Bind(Prefix = "StartPoint")] Address start, 
    [Bind(Prefix = "EndPoint")] Address end 
) 
{ 
    ... 
} 
+0

您能澄清第一個答案的含義嗎?你如何正確綁定? – BlueChippy 2011-06-06 20:20:31