我使用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的一些屬性綁定到一個隱藏的輸入,則動作正確地接收所有的字段...只是想知道有沒有另一種方法。
向我們顯示您的控制器操作代碼。 – Jasen
此外,這[回答](http://stackoverflow.com/questions/2080355/asp-net-mvc-bind-array-in-model)可能會有所幫助。 – Jasen
我添加了控制器動作 – user3170129