1
동적으로 생성 된 각 DOM 요소에 첨부 된 사용자 정의 이름 속성을 사용하여 knockout.js로 만든 양식 요소로 일부 서버 측 모델 바인딩을 수행하고 싶습니다. 나는 AJAX를 사용할 수 있지만 네이티브 HTML 폼 포스트가 나에게 더 잘 작동 할 수 있다는 것을 알고있다.knockout.js로 ASP.NET MVC 모델 바인딩
function MyModel(){
var self = this;
var count = 0;
var insertItem = function(eleToInsertAfter){
var index = self.items.indexOf(eleToInsertAfter),
notFound = -1;
var item = {
type: '',
description: ''
};
if(index == notFound){
self.items.push(item); // there are no items yet, just push this item
} else {
self.items.spilce(++index, 0, item); // insert after the 'eleToInsertAfter' index
}
++count;
}
self.title = ko.observable('');
self.items = ko.observableArray([]);
self.insert = function(eleToInsertAfter){
insertItem(eleToInsertAfter);
}
// insert the first item
self.insert({
type: '',
description: ''
});
}
ko.applyBindings(new MyModel());
및 HTML 태그는 다음과 같습니다 : :이 JS 파일은 다음과 같다 내가 위의 효과를 얻을 수있는 경우
<form method="post" action="/controller/action/">
<input type="text" data-bind="value: title" />
<ol data-bind="foreach: items">
<li>
<!--I'd like to achieve this effect *name="[0].type"* and *name="[0].description"*, and so on -->
<input type="text" data-bind="value: type, *attr: {name = '['+$index+'].type'}*" />
<input type="text" data-bind="value: description, *attr: {name = '['+$index+'].description'}*" /><br />
<button data-bind="click: $root.insert">Add Item</button>
</li>
</ol>
<input type="submit" value="Submit" />
</form>
다음 MVC의 컨트롤러 액션은 다음과 같이 수 :
public ActionResult action(MyModelCS model){
// do something
return View();
}
같을 것이다
및 MyModelCS :
public class MyModelCS {
public string title { get; set; }
public string[] type { get; set; }
public string[] description { get; set; }
}
jQuery를 사용하여 비슷한 버전을 구현했지만 지금은 Knockout.js를 사용하여 유사한 버전을 수행해야합니다. , $index()
<input type="text"
data-bind="value: type, attr: {name = '['+$index()+'].type'}" />
<input type="text"
data-bind="value: description, attr: {name = '['+$index()+'].description'}" />
감사 nemesv : –