2014-01-07 19 views
0

我使用knockout lib創建動態用戶輸入,但是當我提交表單時服務器端並未包含我最初發送的所有數據;我正在使用包含IEnumerable屬性的模型。該視圖指定模型是ReportModel,並且如果我調試JS,我能夠正確地看到所有字段的fieldValue更改。我也使用Html.BeginForm ...發佈表單,並在控制器中執行我的操作,我只需獲得第一個字段(總是第一個),如果它有幫助,那麼我得到的值是正確的(我設置的那個與輸入)Knockout MVC asp.net如何將模型傳回服務器

我的服務器端模型:

public class ReportField 
{ 
    public string fieldName {get; set;} 
    public string fieldValue {get; set;} 
    //other properties 
} 
public class ReportModel 
{ 
    ReportFieldpublic List<ReportField> fields{ get; set; } 
} 

這裏是我的客戶端代碼:

var viewModel = { reportModel: ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)))}; 
$(document).ready(function() { 
    ko.applyBindings(viewModel); 
}; 

,並綁定到輸入:

//...foreach 
<input type="text" data-bind="value: fieldValue, attr: { name: ' + fieldName() +'}" /> 

歡迎任何幫助,謝謝!

編輯:當我綁定ReportField的其他屬性與隱藏輸入,然後在服務器端我得到所有我的字段和值正確...爲什麼?我怎麼能發送所有的字段到服務器,並避免使用輸入隱藏?

控制器動作:

[HttpPost] 
public ActionResult myAction(ReportModel model) 
{ 
    foreach(ReportField field in model.fields){ 
     //model.fields only have one item when I not bind of the other properties on a hidden 
    } 
    //rest of the code 
} 

形式提交:

@using (Html.BeginForm("myAction", "Controller", FormMethod.Post, new { @id = "reportForm" })) 

<input type="submit" value="OK" /> 

$(document).ready(function() { 
    $("#reportForm").submit(function() { 
       var valid = isValidForm();      
       return valid; 
      }); 
} 

迄今爲止的解決方法是ReportField的一些屬性綁定到一個隱藏的輸入,則動作正確地接收所有的字段...只是想知道有沒有另一種方法。

+1

向我們顯示您的控制器操作代碼。 – Jasen

+0

此外,這[回答](http://stackoverflow.com/questions/2080355/asp-net-mvc-bind-array-in-model)可能會有所幫助。 – Jasen

+0

我添加了控制器動作 – user3170129

回答

0

使您的「myAction」成爲帖子。然後模型將被傳遞。

+0

myAction是HttpPost – user3170129

0

我建議你爲此建立你自己的模型活頁夾。如果我正確理解這一點,那麼您正在從動態發送的字段創建表單。

問題是,當參數傳遞回來時,它們會單獨傳遞。 MVC模型聯編程序將無法將其作爲列表放回到一起,因爲它不知道如何執行此操作。內置的模型聯編程序將根據命名參數進行轉換。

請參閱this answer

相關問題