首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用文本框值在单选按钮上设置值

如何使用文本框值在单选按钮上设置值
EN

Stack Overflow用户
提问于 2018-08-16 21:16:37
回答 2查看 101关注 0票数 0

我的模型中有一个属性,它定义了用户要插入的数量。

为此,我使用了3个单选按钮,如下所示:

我使用的代码如下:

代码语言:javascript
复制
<div>
    @Html.RadioButtonFor(m => m.LabelsQuantity, "100", new { @class = "custom-control-inline radiobtn" }) @Html.Label("100", new { @class = "custom-label-inline " })
</div>
<div>
    @Html.RadioButtonFor(m => m.LabelsQuantity, "1000", new { @class = "custom-control-inline radiobtn" }) @Html.Label("1000", new { @class = "custom-label-inline " })
</div>
<div>
    @Html.RadioButtonFor(m => m.LabelsQuantity, "Other"  , new { @class = "custom-control-inline radiobtn" }) @Html.Label("Others", new { @class = "custom-label-inline " })
</div>
<div>
    @Html.TextBoxFor(m => m.LabelsQuantity, string.Empty, new { @class = "custom-control-inline form-control enable_tb", type = "number", disabled = "true" })
</div>

问题是,我在文本框中插入的值并没有传递给控制器,而是传递给了另一个字符串。

我需要能够覆盖视图中的值,或者能够在控制器中获取文本框中的值。

有什么帮助吗?谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-16 21:23:46

视图模型需要第二个属性来绑定textbox。DefaultModelBinder只绑定第一个匹配的名称/值对,因此它在请求中看到LabelsQuantity=Other,并将其设置为您的LabelsQuantity属性,并忽略LabelsQuantity=ValueFormTheTextBox

更改模型以包含一个附加属性,例如

代码语言:javascript
复制
public string OtherQuantity { get; set; }

并在视图中使用

代码语言:javascript
复制
@Html.TextBoxFor(m => m.OtherQuantity)

还应考虑应用条件验证属性,如foolproof [RequiredIf("LabelsQuantity", "Other"]属性,以便获得客户端和服务器端验证

另请注意,如果textbox的值应始终为数字,则应将属性设置为int而不是string

票数 1
EN

Stack Overflow用户

发布于 2018-08-16 21:23:18

您需要为Others文本框引入另一个属性,该属性将发布该文本框的值:

代码语言:javascript
复制
<div>
    @Html.RadioButtonFor(m => m.LabelsQuantity, "100", new { @class = "custom-control-inline radiobtn" }) @Html.Label("100", new { @class = "custom-label-inline " })
</div>
<div>
    @Html.RadioButtonFor(m => m.LabelsQuantity, "1000", new { @class = "custom-control-inline radiobtn" }) @Html.Label("1000", new { @class = "custom-label-inline " })
</div>
<div>
    @Html.RadioButtonFor(m => m.LabelsQuantity, "Other"  , new { @class = "custom-control-inline radiobtn" }) @Html.Label("Others", new { @class = "custom-label-inline " })
</div>
<div>
    @Html.TextBoxFor(m => m.Others, string.Empty, new { @class = "custom-control-inline form-control enable_tb", type = "number", disabled = "true" })
</div>

在模型中:

代码语言:javascript
复制
public class ViewModel
{
    public string LabelsQuantity { get; set; }
    ...............
    ...............
    public string Others { get; set; }
}

现在,在控制器中,您需要使用文本框中提供的选定值检查单选按钮others是否被选中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51878026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档