In first,I have to create some radio buttons in a mvc3 partial view.
When I'm on the screen I need to select only one radio button and retrieved a specific value.
How can I do this (with JS or C# for example) ?
<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>
Thanks in advance !
Ars_n
So you need a group of radiobuttons? I use a custom helper for that.
Code for the helper:
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());
}
now in your view you can just use:
@Html.RadioButtonForSelectList(model => model.yourproperty, Model.listUsedToPopulate)
Now you'll only be able to check one of the radiobuttons at the time. The checked value is stored in model.yourproperty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With