다음과 같은 클래스 및 컨트롤러 작업 방법이 제공됩니다.
public School
{
public Int32 ID { get; set; }
publig String Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street1 { get; set; }
public string City { get; set; }
public String ZipCode { get; set; }
public String State { get; set; }
public String Country { get; set; }
}
[Authorize(Roles = "SchoolEditor")]
[AcceptVerbs(HttpVerbs.Post)]
public SchoolResponse Edit(Int32 id, FormCollection form)
{
School school = GetSchoolFromRepository(id);
UpdateModel(school, form);
return new SchoolResponse() { School = school };
}
그리고 다음과 같은 형태 :
<form method="post">
School: <%= Html.TextBox("Name") %><br />
Street: <%= Html.TextBox("Address.Street") %><br />
City: <%= Html.TextBox("Address.City") %><br />
Zip Code: <%= Html.TextBox("Address.ZipCode") %><br />
Sate: <select id="Address.State"></select><br />
Country: <select id="Address.Country"></select><br />
</form>
School 인스턴스와 학교의 Address 멤버를 모두 업데이트 할 수 있습니다. 이것은 꽤 좋다! ASP.NET MVC 팀 감사합니다!
그러나 jQuery를 사용하여 드롭 다운 목록을 선택하여 미리 채울 수 있습니까? 이 서버 측을 수행 할 수는 있지만 페이지에 목록에 영향을 미치는 다른 동적 요소가 있음을 알고 있습니다.
다음은 내가 지금까지 얻은 내용이며 선택기가 ID와 일치하지 않으므로 작동하지 않습니다.
$(function() {
$.getJSON("/Location/GetCountryList", null, function(data) {
$("#Address.Country").fillSelect(data);
});
$("#Address.Country").change(function() {
$.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
$("#Address.State").fillSelect(data);
});
});
});
답변
에서 Google 그룹스 :
각 특수 문자 앞에 두 개의 백 슬래시를 사용하십시오.
jQuery 선택기의 백 슬래시는 다음 문자를 이스케이프합니다. 그러나 백 슬래시는 JavaScript 문자열의 이스케이프 문자이기 때문에 두 개가 필요합니다. 첫 번째 백 슬래시는 두 번째 백 슬래시를 이스케이프하여 문자열에 실제 백 슬래시를 제공합니다. 그런 다음 jQuery의 다음 문자를 이스케이프합니다.
네가보고있는 것 같아
$(function() {
$.getJSON("/Location/GetCountryList", null, function(data) {
$("#Address\\.Country").fillSelect(data);
});
$("#Address\\.Country").change(function() {
$.getJSON("/Location/GetRegionsForCountry", { country: $(this).val() }, function(data) {
$("#Address\\.State").fillSelect(data);
});
});
});
또한 체크 아웃 내가 CSS 표기법에 사용 된 문자가있는 ID로 요소를 선택하려면 어떻게합니까? jQuery FAQ에서.
답변
id에 공백이 있으면 jQuery id 선택기를 사용할 수 없습니다. 속성 선택기를 사용하십시오.
$('[id=foo bar]').show();
가능하면 요소 유형도 지정하십시오.
$('div[id=foo bar]').show();
답변
Jquery를 위해 탈출하십시오.
function escapeSelector(s){
return s.replace( /(:|\.|\[|\])/g, "\\$1" );
}
사용 예 :
e.find('option[value='+escapeSelector(val)+']')
더 많은 정보는 여기에 .
답변
방금 릴리스 된 ASP.NET MVC의 릴리스 후보는이 문제를 해결하여 이제 점을 ID 속성의 밑줄로 바꿉니다.
<%= Html.TextBox("Person.FirstName") %>
렌더링
<input type="text" name="Person.FirstName" id="Person_FirstName" />
자세한 내용은 14 페이지부터 릴리스 정보를 참조하십시오.
답변
이것은 jQuery Selectors docs에 설명되어 있습니다 .
메타 문자 (예
!"#$%&'()*+,./:;<=>?@[\]^`{|}~
:)를 이름의 리터럴 부분으로 사용하려면 두 개의 백 슬래시로 이스케이프해야합니다\\
. 예를 들어,가있는 요소
id="foo.bar"
는 선택기를 사용할 수 있습니다$("#foo\\.bar")
.
즉, 접두사 .
와 함께 \\
다음과 같이 :
$("#Address\\.Country")
왜 .
아이디가 작동 하지 않습니까?
문제는 .
특별한 의미 가 있다는 것입니다. 다음 문자열은 클래스 선택기로 해석됩니다. 그래서 $('#Address.Country')
일치합니다<div id="Address" class="Country">
.
로 이스케이프 \\.
하면 점은 특별한 의미없이 일반 텍스트로 취급되며 원하는 ID와 일치합니다 <div id="Address.Country">
.
이것은 !"#$%&'()*+,./:;<=>?@[\]^`{|}~
그렇지 않으면 jQuery의 선택기로 특별한 의미를 갖는 모든 문자에 적용됩니다 . 그냥 \\
일반 텍스트로 취급하기 만하면 됩니다.
왜 2 \\
입니까?
bdukes 답변에서 언급했듯이 2 \
문자 가 필요한 이유가 있습니다 . \
JavaScript에서 다음 문자를 이스케이프합니다. 자바 스크립트 문자열을 해석 자체 때 "#Address\.Country"
, 그것은을 볼 수 \
의미하는 것으로 해석 litterally 다음과 같은 특성을 가지고 및 제거 문자열이에 인수로 전달 될 때를 $()
. 즉, jQuery는 여전히 문자열을"#Address.Country"
합니다.
두 번째 \
게임이 시작됩니다. 첫 번째는 두 번째 문자를 특수 문자가 아닌 문자로 해석하도록 JavaScript에 지시합니다. 이것은 두 번째 .
문자가 jQuery에 표시되고 다음 문자가 리터럴 문자 임을 이해한다는 의미 입니다.
휴! 어쩌면 우리는 그것을 시각화 할 수 있습니다.
// Javascript, the following \ is not special.
// |
// |
// v
$("#Address\\.Country");
// ^
// |
// |
// jQuery, the following . is not special.
답변
두 개의 백 슬래시를 사용하면 괜찮습니다. 그러나 동적 이름을 사용하는 경우 변수 이름이므로 문자를 바꿔야합니다.
변수 이름을 변경하지 않으려면 다음을 수행하십시오.
var variable="namewith.andother";
var jqueryObj = $(document.getElementById(variable));
jquery 객체보다.
답변
추가 정보 만 :이 ASP.NET MVC 문제 # 2403을 확인하십시오 .
문제가 해결 될 때까지 Html.TextBoxFixed 등과 같은 내 자신의 확장 메서드를 사용하여 id 속성 (이름 속성이 아닌)의 점을 밑줄로 간단히 대체하므로 $ ( “# Address_Street”)와 같은 jquery를 사용하십시오 그러나 서버에서는 Address.Street와 같습니다.
샘플 코드는 다음과 같습니다.
public static string TextBoxFixed(this HtmlHelper html, string name, string value)
{
return html.TextBox(name, value, GetIdAttributeObject(name));
}
public static string TextBoxFixed(this HtmlHelper html, string name, string value, object htmlAttributes)
{
return html.TextBox(name, value, GetIdAttributeObject(name, htmlAttributes));
}
private static IDictionary<string, object> GetIdAttributeObject(string name)
{
Dictionary<string, object> list = new Dictionary<string, object>(1);
list["id"] = name.Replace('.', '_');
return list;
}
private static IDictionary<string, object> GetIdAttributeObject(string name, object baseObject)
{
Dictionary<string, object> list = new Dictionary<string, object>();
list.LoadFrom(baseObject);
list["id"] = name.Replace('.', '_');
return list;
}
