Knockout.js 및 체크박스 목록:MVC 컨트롤러에 게시
문제
다음과 같은 MVC 뷰 모델이 있습니다.
public class DirectorySearchModel
{
[Display(Name = "First name contains")]
public string FirstName { get; set; }
[Display(Name = "Last name contains")]
public string LastName { get; set; }
public CountriesCollection Countries { get; set; }
public IEnumerable<Country> SelectedCountries { get; set; }
public IEnumerable<Country> AllCountries { get; set; }
}
CountriesCollection 개체(9행)는 다음과 같습니다.
public class CountriesCollection
{
[Display(Name = "Countries")]
public int[] arrCountries { get; set; }
}
이제 CountriesCollection의 빈 인스턴스를 새로 만든 다음 이를 DirectorySearchModel 보기 모델의 빈 인스턴스에 추가하고 Knockout.js에 대한 javascript 보기 모델로 모두 직렬화합니다.
{
"FirstName":null,
"LastName":null,
"Countries":{"arrCountries":[]},
"SelectedCountries":[{"RelationshipManager":{},"CountryId":1,"CountryName":"UK"},{"RelationshipManager":{},"CountryId":2,"CountryName":"France"},{"RelationshipManager":{},"CountryId":3,"CountryName":"Spain"}],
"AllCountries":[{"RelationshipManager":{},"CountryId":1,"CountryName":"UK"},{"RelationshipManager":{},"CountryId":2,"CountryName":"France"},{"RelationshipManager":{},"CountryId":3,"CountryName":"Spain"}]
}
내 확인란은 다음과 같이 렌더링됩니다. <input checked="checked" data-bind="checked: Countries.arrCountries" id="Countries_arrCountries30" name="Countries.arrCountries" type="checkbox" value="1">
.몇 가지를 확인하면 다음과 같은 Knockout.js 뷰 모델이 생성됩니다.
{
"FirstName":null,
"LastName":null,
"Countries":{"arrCountries":["1", "3"]},
"SelectedCountries":[{"RelationshipManager":{},"CountryId":1,"CountryName":"UK"},{"RelationshipManager":{},"CountryId":2,"CountryName":"France"},{"RelationshipManager":{},"CountryId":3,"CountryName":"Spain"}],
"AllCountries":[{"RelationshipManager":{},"CountryId":1,"CountryName":"UK"},{"RelationshipManager":{},"CountryId":2,"CountryName":"France"},{"RelationshipManager":{},"CountryId":3,"CountryName":"Spain"}]
}
내 의견을 정상적으로 제출합니다(예:Knockout.js가 아닌 제출 버튼을 통해) DirectorySearchModel
, 나는 요청할 수 있습니다 model.Countries.arrCountries
확인된 항목의 목록을 얻으려면 다음을 사용합니다.
$.post("/MyController/MyAction", ko.toJS(viewModel), function(returnData) {
$("#resultCount").html(returnData);
});
또는...
$.post("/MyController/MyAction", viewModel, function(returnData) {
$("#resultCount").html(returnData);
});
같은 것을 기대하는 다른 행동으로 DirectorySearchModel
, model.Countries.arrCountries
항상 null
!Knockout.js가 게시한 때문인지 궁금합니다. arrCountries
다음과 같은 항목 string[]
MVC가 예상하는 경우 int[]
s, 하지만 예상대로 MVC 코드를 변경합니다. string[]
별로 달라진 게 없는 것 같아요..!그만큼 CountriesCollection
내의 개체 DirectorySearchModel
존재하는 것 같지만 그것은 arrCountries
그 안에는 언제나 null
.
어떤 아이디어가 있나요?도움을 주시면 감사하겠습니다!
편집하다
Knockout.js viewModel을 수신하는 작업:
public MvcHtmlString ResultCount(DirectorySearchModel model)
{
return new MvcHtmlString(getResultCount(model).ToString());
}
그만큼 getResultCount
방법:
public int getResultCount(DirectorySearchModel model)
{
IUserRepository userRepository = new UserRepository();
int count = userRepository.Search(model, null).Count();
return count;
}
결정된!
$.post에서 $.ajax로 간단히 전환하여 Knockout.js 뷰 모델을 mvc 작업으로 다시 보내는 것이 전부라는 점을 지적해준 Konstantin에게 감사드립니다!내가 사용하는 $.ajax 코드는 다음과 같습니다.
$.ajax({
type: "POST",
url: "/MyController/MyAction",
data: ko.toJSON(viewModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#resultCount").html(data);
}
});
해결책
$.post를 사용할 수 없습니다. 기본 $.ajax로 이동하여 올바른 콘텐츠 유형을 추가하여 mvc가 게시된 json을 수락하고 모델 바인딩을 수행하도록 해야 합니다(콘텐츠 유형은 "application/json;이어야 합니다.")charset=utf-8") Google에서 검색하면 많은 예제를 볼 수 있습니다.