【发布时间】:2010-12-07 20:46:12
【问题描述】:
我有一个强类型对象,它代表表单的所有文本框属性,当我发布到控制器时它工作正常。
我现在需要在这个表单中添加一个单选按钮。这如何映射到强类型对象?
【问题讨论】:
我有一个强类型对象,它代表表单的所有文本框属性,当我发布到控制器时它工作正常。
我现在需要在这个表单中添加一个单选按钮。这如何映射到强类型对象?
【问题讨论】:
如果您使用 HtmlHelper.RadioButton,只要名称与您的属性名称匹配就可以了。
以下是我的一个项目中的一段代码:
<span><%= Html.RadioButton("DateFormat", "MMMM/dd/yy", Model.DateFormat.Equals("MMMM/dd/yy"), new Dictionary<string, object> { { "class", "normalwidth" } })%><label class="displayinline"><%=DateTime.Now.ToString("MMMM dd, yyyy")%></label></span>
<span><%= Html.RadioButton("DateFormat", "yyyy/MM/dd", Model.DateFormat.Equals("yyyy/MM/dd"), new Dictionary<string, object> { { "class", "normalwidth" } })%><label class="displayinline"><%=DateTime.Now.ToString("yyyy/MM/dd")%></label></span>
<span><%= Html.RadioButton("DateFormat", "dd/MM/yyyy", Model.DateFormat.Equals("dd/MM/yyyy"), new Dictionary<string, object> { { "class", "normalwidth" } })%><label class="displayinline"><%=DateTime.Now.ToString("dd/MM/yyyy")%></label></span>
<span><%= Html.RadioButton("DateFormat", "", new Dictionary<string, object> { { "class", "normalwidth" } })%><label class="displayinline">custom <%= Html.TextBox("customdate", "", new Dictionary<string, object> { { "style", "width:50px; font-size:12px; display:inline;" } }) %> </label></span>
这里是渲染的 HTML。请注意,每个输入具有相同的名称,但值不同。只有选定按钮的值才会回传到服务器。
<p><label>Date Format</label>
<span><input class="normalwidth" id="DateFormat" name="DateFormat" type="radio" value="MMMM/dd/yy" /><label class="displayinline">October 18, 2009</label></span>
<span><input checked="checked" class="normalwidth" id="DateFormat" name="DateFormat" type="radio" value="yyyy/MM/dd" /><label class="displayinline">2009/10/18</label></span>
<span><input class="normalwidth" id="DateFormat" name="DateFormat" type="radio" value="dd/MM/yyyy" /><label class="displayinline">18/10/2009</label></span>
<span><input class="normalwidth" id="DateFormat" name="DateFormat" type="radio" value="" /><label class="displayinline">custom <input id="customdate" name="customdate" style="width:50px; font-size:12px; display:inline;" type="text" value="" /> </label></span>
</p>
在你的课堂上:
public class Post
{
public string DateFormat {get; set:}
}
【讨论】:
@Html.RadioButtonFor(m => m.DateFormat, "MMMM/dd/yy")
@Html.RadioButtonFor(m => m.DateFormat, "yyyy/MM/dd")
【讨论】: