gpt4 book ai didi

c# - MVC3 (Razor) 单选按钮检查

转载 作者:搜寻专家 更新时间:2023-11-01 04:50:44 24 4
gpt4 key购买 nike

首先,我必须在 mvc3 局部 View 中创建一些单选按钮。

当我在屏幕上时,我只需要选择一个单选按钮并检索特定值。

我该怎么做(例如使用 JS 或 C#)?

            <div id="UserDeleteInfosField">
<p>
@Html.RadioButton("HasUserLeave", new { id = "rb1" })
@UserAccountResources.UserLeave
@Html.HiddenFor(x => x.UserLeave)
</p>
<br />
<p>
@Html.RadioButton("HasUserTransfer", new { id = "rb2" })
@UserAccountResources.UserTransfer
@Html.HiddenFor(x => x.UserTransfer)
</p>
<br />
<p>
@Html.RadioButton("HasUserDetachment", new { id = "rb3" })
@UserAccountResources.UserDetachment
@Html.HiddenFor(x => x.UserDetachment)
</p>
<br />
<p>
@Html.RadioButton("HasUserRetirement", new { id = "rb4" })
@UserAccountResources.UserRetirement
@Html.HiddenFor(x => x.UserRetirement)
</p>
<br />
<p>
@Html.RadioButton("HasUserStatus", new { id = "rb5" })
@UserAccountResources.UserStatus
@Html.HiddenFor(x => x.UserStatus)
</p>
</div>

提前致谢!

Ars_n

最佳答案

所以你需要一组单选按钮?为此,我使用了自定义助手。

助手代码:

public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();

if (listOfValues != null)
{
// Create a radio button for each item in the list
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);

// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));

var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();

if (item.Selected)
{
radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id, @checked = "checked", }).ToHtmlString();
}


// Create the html string that will be returned to the client
// e.g. <input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line1</label>
sb.AppendFormat("<div class=\"RadioButton\">{0}{1}</div>", radio, label);
}
}

return MvcHtmlString.Create(sb.ToString());
}

现在在您的 View 中您可以使用:

@Html.RadioButtonForSelectList(model => model.yourproperty, Model.listUsedToPopulate)

现在您一次只能选中其中一个单选按钮。选中的值存储在 model.yourproperty 中。

关于c# - MVC3 (Razor) 单选按钮检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13118764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com