基于模型的asp.net mvc3检查单选按钮 [英] asp.net mvc3 checking radio button based on model

查看:73
本文介绍了基于模型的asp.net mvc3检查单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项看似简单的任务,即根据模型的布尔值将单选按钮设置为选中".我的模型"IsSDPDonor"中有一个布尔值,我想将其用于是/否"单选按钮.如果"IsSDPDonor"为true,则应检查"Yes"单选按钮,如果为false,则应检查"No"单选按钮.我尝试使用下面的代码,但始终检查否"单选按钮.

I have a seemingly easy task of setting a radio button "checked" based on model's boolean value. I have a boolean in my model "IsSDPDonor" which I want to use it for Yes/No Radio buttons. The "Yes" radio button should be checked if "IsSDPDonor" is true and "No" radio button when it is false. I tried to use the code below but it always checks the "No" radio button.

 @Html.Label("Would You Like to Donate Platelets (SDP)") : 
 @Html.RadioButtonFor(m => m.Donor.IsSDPDonor, true, new {@checked = Model.Donor.IsSDPDonor ? "checked" : ""}) Yes 
 @Html.RadioButtonFor(m => m.Donor.IsSDPDonor, false, new { @checked = !Model.Donor.IsSDPDonor ? "checked" : "" }) No

我有点沮丧,所以我想我应该帮些忙.基本上,HTML语法表示只放置"Checked"属性,不带任何值来检查单选按钮.我想知道如何使用MVC3剃须刀语法来做到这一点.

I was getting a little frustrated, so I thought that I would rather take some help. Basically, the HTML syntax says to put only the "Checked" attribute without any values to check a radio button. I was wondering how would I do that using MVC3 razor syntax.

推荐答案

在代码块中创建HTML选项,如果不应选中该按钮,则将它们保留为空,然后在帮助器中使用适当的变量.

Create the HTML options in a code block, leaving them null if the button shouldn't be checked, then use the proper variable in your helper.

@{
    var yesOptions = Model.Donor.IsSDPDonor ? new { @checked = "checked" } : null;
    var noOptions =  Model.Donor.IsSDPDonor ? null : new { @checked = "checked" };
}
@Html.Label("Would You Like to Donate Platelets (SDP)") : 
@Html.RadioButtonFor(m => m.Donor.IsSDPDonor, true, yesOptions ) Yes 
@Html.RadioButtonFor(m => m.Donor.IsSDPDonor, false, noOptions ) No

编辑:在查看源代码之后,对我来说,它应该根据模型的值来设置此属性.您是否尝试过完全省略HTML属性?

EDIT: After looking at the source code, it appears to me that it should be setting this property based on the value of the model. Have you tried omitting the HTML attributes completely?

case InputType.Radio:
    if (!usedModelState) {
        string modelStateValue = htmlHelper.GetModelStateValue(name, typeof(string)) as string;
        if (modelStateValue != null) {
            isChecked = String.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);
            usedModelState = true;
        }
    }
    if (!usedModelState && useViewData) {
        isChecked = htmlHelper.EvalBoolean(name);
    }
    if (isChecked) {
        tagBuilder.MergeAttribute("checked", "checked");
    }
    tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
    break;

这篇关于基于模型的asp.net mvc3检查单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆