MVC - 需要文本框中填写时所选择的单选按钮 [英] MVC - Require text box filled in when radio button selected

查看:79
本文介绍了MVC - 需要文本框中填写时所选择的单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找出解决此问题的最佳方法.

Trying to figure out the best way to handle this.

我需要在需要的地方有逻辑:1)如果颜色类型允许数量,则为数量.
2)信用卡(如果适用)(目前仅允许使用一种颜色).

I need to have logic in where it requires: 1) the Amount if a the color type allows an amount.
2) Credit cards if applicable (only allowed on 1 color at this time).

在视图中,我具有必需的验证器,但是由于它适用于金额,因此它显示所有金额,而不仅仅是所选单选按钮的文本框.

In the View, I had the required validator however since it applies to the Amount, it shows on ALL amounts, not just the textbox for the radio button selected.

我已经尝试过jQuery在单击时将Required属性放在字段上,但是当我对其进行设置时,它似乎适用于每个项目:示例:$('#TxtColorType_Green').rules("add","required");

I've tried jQuery to put Required attributes on the fields when clicked but seems like when I set it it applies to every item: Example: $('#TxtColorType_Green').rules("add", "required");

示例屏幕截图

以下示例演示了其工作方式:

  1. 红色-允许使用一定金额,但不使用信用卡
  2. 绿色-允许使用金额和信用卡
  3. 蓝色-不允许金额

模型

public class ColorSelected
{
    [Required(ErrorMessage = "Color Required")]
    [Display(Name = "Color Type:")]
    public string ColorTypeId { get; set; }

    // [Required(ErrorMessage = "Color Amount Required")]  since Radio Button, need to set Required attribute when selected **
    [Display(Name = "Color Amount:")]
    public decimal? CostAmt { get; set; }
}

public class ColorType
{
    Public String ColorTypeId;
    Public String ColorTypeShortDesc;
    Public String Description;
    Public String AmountDescription;
    Public String DefaultChoice;
    public bool? DefaultChoice { get; set; }
    public bool? AllowCreditCard { get; set; }

    public ColorType()
    {
        init();
    }
}

public class ColorTypeRed : ColorType
{
    public override void init()
    {
        ColorTypeId = "R";
        ColorTypeShortDesc = "Red";
        Description = "Red";
        AmountDescription = "Pay Later.";
        DefaultChoice = true;
    }
}

public class ColorTypeGreen : ColorType
{
    public override void init()
    {
        ColorTypeId = "G";
        ColorTypeShortDesc = "Gr";
        Description = "Green";
        AmountDescription = "Pay Now";
        AllowCreditCard = true;    
    }
}

public class ColorTypeBlue : ColorType
{
    public override void init()
    {
        ColorTypeId = "B";
        ColorTypeShortDesc = "Bl";
        Description = "Blue";
        AmountDescription = null;
    }
}

ViewModel

        public class ColorViewModel
        {
            public ColorSelected colorSelected;
            public List<ColorType> ColorTypes;
            public ColorViewModel()
            {
                ColorTypes.Add(new ColorTypeBlue());
                ColorTypes.Add(new ColorTypeRed());
                ColorTypes.Add(new ColorTypeGreen());

            }
        }

查看

    @model ColorViewModel
    <div id="divColorType" class="ec-radiobtnlist">
        @{
            foreach (var ColorType in Model.ColorTypes)
            {
                var idVal = string.Format("ColorType_{0}", ColorType.ColorTypeShortDesc);
                <div>
                    <label>
                        @Html.RadioButtonFor(m => m.ColorSelected.ColorTypeId,
                                            ColorType.ColorTypeId,
                                            new { id = string.Format("Rb{0}", idVal) }
                                        )
                        <span>@ColorType.Description</span>
                    </label>

                    @{
                        if (ColorType.AmountDescription != null)
                        {
                            <text>
                                @Html.TextBoxFor(m => m.ColorSelected.CostAmt,
                                        new { @id = string.Format("TxtAmt{0}", idVal), @class = "txtAmt", @maxlength = "10", @size = "3" }).00,
                                @Html.Raw(ColorType.AmountDescription)
                                @*@Html.ValidationMessageFor(m => m.ColorSelected.CostAmt)  Unfortunately right now if put this in the error will occur on ALL Color types as it uses the same property*@
                            </text>
                        };
                        if (ColorType.AllowCreditCard == true)
                        {
                            <div id=@string.Format("{0}_PmtCC", idVal)>
                                @Html.Partial("_CreditCardDetails")
                            </div>
                        };
                    }
            </div>
            }
        }
    </div>

预先感谢!

推荐答案

编码失败的原因有多种,包括为同一属性( CostAmt )和 DefaultModelBinder 将仅绑定第一个值(因此,如果选择"Green",则将绑定与"Red"关联的文本框的值).实际上,POST方法不会绑定任何内容,因为您的视图模型仅包含字段,而没有属性.

There are multiple reasons why you code will fail, including that your generating multiple textboxes for the same property (CostAmt) and the DefaultModelBinder will only bind the first value (so if you select 'Green', the value of the textbox associated with 'Red' will be bound). In fact nothing will be bound in the POST method because your view model contains only fields, not properties.

要同时进行客户端和服务器端验证,您需要使用实现 IClientValidatable 的条件验证属性,例如万无一失 [RequiredIf("SelectedColor","G")] 应用于描述信用卡"的属性,并且这些属性也必须在视图中模型.AFAIK,没有开箱即用的东西可以处理多个值(红色"或绿色")的"RequiredIf",但是您可以从

To have both client and server side validation, you need to use a conditional validation attribute that implements IClientValidatable, for example a foolproof [RequiredIf("SelectedColor", "G")] applied to the properties describing the 'CreditCard', and those properties must also be in the view model. AFAIK, there is nothing out of the box to handle a 'RequiredIf' for multiple values ('Red' or 'Green'), but you can download my RequiredIfContains attribute from GitHub

您的视图模型应该是

public class ColorViewModel
{
    public string SelectedColor { get; set; } // set this to "R" or "G" or "B" initially to select a radio button
    public bool IsAmountHidden { get; set; } // set based on the value of SelectedColor
    public bool IsCreditCardHidden { get; set; }
    public List<ColorType> ColorTypes { get; set; }
    [RequiredIfContains("SelectedColor", "R, G")] // custom validation attribute
    public decimal? Amount { get; set; } // not clear why this is decimal when your view shows the fractions as .00
    [RequiredIf("SelectedColor", "G")]
    public string SelectedCreditCard { get; set; }
    ... more properties of Credit Card
    public IEnumerable<SelectListItem> CreditCardTypeList { get; set; }
}

然后在视图中

// Generate radio buttons
@foreach (var ColorType in Model.ColorTypes)
{
    <label>
        @Html.RadioButtonFor(m => m.SelectedColor, ColorType.ColorTypeId, new { id = "", @class = "color" })
       <span>@ColorType.Description</span>
    </label>
}
// Generate textbox
@{ var amountClass = Model.IsAmountHidden ? "hidden" : null; }
<div id="cost" class="@amountClass ">
    @Html.TextBoxFor(m => m.Amount)
    @Html.ValidationMessageFor(m => m.Amount)
</div>
// Generate credit card controls
@{ var creditCardClass = Model.IsCreditCardHidden ? "hidden" : null; }
<div id="creditcard" class="@creditCardClass">
    @Html.DropDownListFor(m => m.SelectedCreditCard, Model.CreditCardTypeList)
    @Html.ValidationMessageFor(m => m.SelectedCreditCard)
    .... // more properties of Credit Card
</div>

使用 display设置 hidden 样式的地方:none;

Where hidden is styled with display: none;

然后,您将需要一些JavaScript来处理单选按钮 .change()事件,以根据所选单选按钮的值切换控件的可见性

You will then need some javascript to handle the radio buttons .change() event to toggle the visibility of the controls based on the value of the selected radio button

$('.color').change(function() {
    var selected = $('.color:checked').val();
    // add or remove the 'hidden' class name based on the value
});

这篇关于MVC - 需要文本框中填写时所选择的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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