이 꽤 잘 정의 모델 바인더 및 일반 HTML을 ... 사용
먼저, 면도기 구문에 HTML 양식 작품 :
@using (Html.BeginForm("Action", "Controller", FormMethod.Post)) {
<ol>
<li><input type="textbox" name="tBox" value="example of another form element" /></li>
<li><input type="checkbox" name="cBox" value="1" /> One</li>
<li><input type="checkbox" name="cBox" value="2" /> Two</li>
<li><input type="checkbox" name="cBox" value="3" /> Three</li>
<li><input type="checkbox" name="cBox" value="4" /> Four</li>
<li><input type="checkbox" name="cBox" value="5" /> Five</li>
<li><input type="submit" /></li>
</ol>
}
(FormMethod.Post
도 .Get
수는 중요하지 않습니다
:
다음)이 대한 적절한 MVC의 의미에서 양식 제출을 나타내는 모델 객체를210
맞춤형 모델 바인더 클래스 (이 모델을 바인딩 된 모델 안에 넣고 싶습니다. 그래서 위에서 만든 모델을 반복하여 추가 할 위치를 보여줍니다.개인 속성 세터를 사용하는 바인더 좋은 일이있다)는 또한 내부에서 허용 걸기
public class CheckboxListExampleModel {
public string TextboxValue { get; private set; }
public List<int> CheckboxValues { get; private set; }
public class Binder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
var model = new CheckboxListExampleModel();
model.TextboxValue = bindingContext.GetValueAsString("tBox");
string checkboxCsv = bindingContext.GetValueAsString("cBox");
// checkboxCsv will be a comma-separated list of the 'value' attributes
// of all the checkboxes with name "cBox" which were checked
model.CheckboxValues = checkboxCsv.SplitCsv<int>();
return model;
}
}
}
.GetValueAsString()
명확성을 위해 사용되는 확장 방법이며, 여기있다 :
public static string GetValueAsString(this ModelBindingContext context, string formValueName, bool treatWhitespaceAsNull = true) {
var providerResult = context.ValueProvider.GetValue(formValueName);
if (providerResult.IsNotNull() && !providerResult.AttemptedValue.IsNull()) {
if (treatWhitespaceAsNull && providerResult.AttemptedValue.IsNullOrWhiteSpace()) {
return null;
} else {
return providerResult.AttemptedValue.Trim();
}
}
return null;
}
.SplitCsv<T>()
는 이고 또한 확장 메서드가 있지만 일반적으로 충분히 필요하고 지저분한 코드이므로 독자에게 연습 문제로 남겨 두겠습니다.
[HttpPost]
public ActionResult Action([ModelBinder(typeof(CheckboxListExampleModel.Binder))] CheckboxListExampleModel model) {
// stuff
}
아이디어가 나쁘지는 않지만이 아닌 다른 항목 양식을 사용할 때 작동하지 않습니다 :
그리고 마지막으로는, 양식을 처리 할 수있는 액션은 제출합니다. 예를 들어 사용자 이름/비밀번호 + 확인란 모음이 있다고하면 작동하지 않습니다./ – Erick
@Erick 물론 작동 할 수 있습니다. 뷰 모델에는'Username'과'Password'와 같은 간단한 속성과 체크 박스 정보를 포함 할 컬렉션 속성 인 IEnumerable가 포함됩니다. 이제 폼에서'Html.EditorForModel'을 사용하는 대신 간단한'<% = Html.TextBoxFor (x => x.Username) %>'와'<% = Html.PasswordFor (x => x.Password) %>와 같은 편집기 템플릿을 렌더링하는 <% = Html.EditorFor (x => x.MyCheckboxes) %>'를 사용합니다. –
나는 이것을 성취하는 많은 방법을 읽었으며 이것은 가장 우아한 해결책이었다. 감사! – JimDaniel