ASP.NET MVC 예 / 아니요 바운드 모델 MVC가있는 라디오 버튼
누구든지 예 / 아니요 라디오 버튼을 ASP.NET MVC에서 강력한 형식의 모델의 부울 속성에 바인딩하는 방법을 알고 있습니다.
모델
public class MyClass
{
public bool Blah { get; set; }
}
전망
<%@ Page Title="blah" Inherits="MyClass"%>
<dd>
<%= Html.RadioButton("blah", Model.blah) %> Yes
<%= Html.RadioButton("blah", Model.blah) %> No
</dd>
감사
해결책:
지시에 대해 Brian에게 감사하지만 그가 쓴 것과 반대였습니다. 따라서-
<%@ Page Title="blah" Inherits="MyClass"%>
<dd>
<%= Html.RadioButton("blah", !Model.blah) %> Yes
<%= Html.RadioButton("blah", Model.blah) %> No
</dd>
두 번째 매개 변수가 선택되었으므로! 부울이 false 일 때 no 값을 선택합니다.
<%= Html.RadioButton("blah", !Model.blah) %> Yes
<%= Html.RadioButton("blah", Model.blah) %> No
MVC 3 및 Razor를 사용하는 경우 다음을 사용할 수도 있습니다.
@Html.RadioButtonFor(model => model.blah, true) Yes
@Html.RadioButtonFor(model => model.blah, false) No
다음은 fieldset
내게 필요한 옵션을 사용 하고 첫 번째 단추를 기본값으로 지정 하는보다 완전한 예 입니다. 이 없으면 fieldset
라디오 버튼의 전체 내용을 프로그래밍 방식으로 결정할 수 없습니다.
모델
public class MyModel
{
public bool IsMarried { get; set; }
}
전망
<fieldset>
<legend>Married</legend>
@Html.RadioButtonFor(e => e.IsMarried, true, new { id = "married-true" })
@Html.Label("married-true", "Yes")
@Html.RadioButtonFor(e => e.IsMarried, false, new { id = "married-false" })
@Html.Label("married-false", "No")
</fieldset>
@checked
익명 객체에 인수를 추가하여 단일 선택 단추를 기본값으로 설정할 수 있습니다 .
new { id = "married-true", @checked = 'checked' }
당신은 대체하여 문자열로 결합 할 수 있습니다 true
및 false
문자열 값.
Ben의 대답을 약간 벗어나서 레이블에 사용할 수 있도록 ID에 대한 속성을 추가했습니다.
<%: Html.Label("isBlahYes", "Yes")%><%= Html.RadioButtonFor(model => model.blah, true, new { @id = "isBlahYes" })%>
<%: Html.Label("isBlahNo", "No")%><%= Html.RadioButtonFor(model => model.blah, false, new { @id = "isBlahNo" })%>
이게 도움이 되길 바란다.
일반 HTML을 사용하여 라디오 버튼 주위에 레이블 태그를 추가하면 'labelfor'문제도 해결됩니다.
<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>
텍스트를 클릭하면 적절한 라디오 버튼이 선택됩니다.
또는 MVC 2.0 :
<%= Html.RadioButtonFor(model => model.blah, true) %> Yes
<%= Html.RadioButtonFor(model => model.blah, false) %> No
모자에 고리를 넣을 수 있다면 라디오 버튼 기능을 재사용하는 기존의 답변보다 더 깨끗한 방법이 있다고 생각합니다.
ViewModel에 다음 속성이 있다고 가정 해 봅시다 .
Public Class ViewModel
<Display(Name:="Do you like Cats?")>
Public Property LikesCats As Boolean
End Class
재사용 가능한 편집기 템플릿을 통해 해당 속성을 노출 할 수 있습니다 .
먼저 파일을 만듭니다 Views/Shared/EditorTemplates/YesNoRadio.vbhtml
그런 다음 YesNoRadio.vbhtml에 다음 코드를 추가하십시오 .
@ModelType Boolean?
<fieldset>
<legend>
@Html.LabelFor(Function(model) model)
</legend>
<label>
@Html.RadioButtonFor(Function(model) model, True) Yes
</label>
<label>
@Html.RadioButtonFor(Function(model) model, False) No
</label>
</fieldset>
You can call the editor for the property by manually specifying the template name in your View:
@Html.EditorFor(Function(model) model.LikesCats, "YesNoRadio")
Pros:
- Get to write HTML in an HTML editor instead of appending strings in code behind.
- Preserves the DisplayName DataAnnotation
- Allows clicks on Label to toggle radio button
- Least possible code to maintain in form (1 line). If something is wrong with the way it is rending, take it up with the template.
I ended up packaging this into an extension method so (1) I could generate the label and radio at once and (2) so I didn't have to fuss with specifying my own IDs:
public static class HtmlHelperExtensions
{
public static MvcHtmlString RadioButtonAndLabelFor<TModel, TProperty>(this HtmlHelper<TModel> self, Expression<Func<TModel, TProperty>> expression, bool value, string labelText)
{
// Retrieve the qualified model identifier
string name = ExpressionHelper.GetExpressionText(expression);
string fullName = self.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
// Generate the base ID
TagBuilder tagBuilder = new TagBuilder("input");
tagBuilder.GenerateId(fullName);
string idAttr = tagBuilder.Attributes["id"];
// Create an ID specific to the boolean direction
idAttr = String.Format("{0}_{1}", idAttr, value);
// Create the individual HTML elements, using the generated ID
MvcHtmlString radioButton = self.RadioButtonFor(expression, value, new { id = idAttr });
MvcHtmlString label = self.Label(idAttr, labelText);
return new MvcHtmlString(radioButton.ToHtmlString() + label.ToHtmlString());
}
}
Usage:
@Html.RadioButtonAndLabelFor(m => m.IsMarried, true, "Yes, I am married")
'development' 카테고리의 다른 글
Matplotlib 컬러 바 크기를 그래프와 일치하도록 설정 (0) | 2020.07.02 |
---|---|
파이썬에서 "내부 예외"(트레이스 백 포함)? (0) | 2020.07.02 |
뮤텍스와 크리티컬 섹션의 차이점은 무엇입니까? (0) | 2020.07.02 |
nginx가 반환 한 서버 헤더를 어떻게 변경합니까? (0) | 2020.07.02 |
장고 디버그 툴바가 표시되지 않음 (0) | 2020.07.02 |