I need to create a simple radio button list selection to choose from the following values:
How would we add it in the following razor view? Is it better to create an enum of these values in the QuestionModel
and use foreach
to bind with html helper.
Any example or ideas?
@model Survey.Models.Question
@using (Html.BeginForm("Index", "Home", new { QuestionId = Model.QuestionId }))
{
<h2>Survey</h2>
<fieldset>
<legend>Please Choose</legend>
<p>
Question ID:
@Model.QuestionId
</p>
<p>
Description:
@Model.Description
</p>
<input type="submit" value="Next" id="submitButton" />
</fieldset>
}
Strongly-typed checks the errors in code at the time of compilation, not at run time. This control is used to create a radiobutton with a specified property. This HTML Helper radio-button is not attached / bound with any Model. You can directly use HTML element of a Radio button.
Razor Radio Buttons. Razor offers two ways to generate radio buttons. The recommended approach is to use the input tag helper. When creating a radio button, you must provide the value of one of the predefined options to the value attribute.
Using the ASP.NET Html Helpers, there are three various methods you can use for each of the different helpers supplied for radio buttons.
Method 1
A simple way to make a radio button list:
<div>
<label>
@Html.RadioButton("Answer", "Agree")
Agree
</label>
</div>
<div>
<label>
@Html.RadioButton("Answer", "Disagree")
Disagree
</label>
</div>
<div>
<label>
@Html.RadioButton("Answer", "Not Sure")
Not Sure
</label>
</div>
Method 2
The above code will post the checked value with a name of "Answer" to the server when you click Submit. If you would like to make this strongly typed, as you did with Model.QuestionId and Model.Description, you could add a Answer property to your model and do the following:
<div>
<label>
@Html.RadioButtonFor(m => m.Answer, "Agree")
Agree
</label>
</div>
<div>
<label>
@Html.RadioButtonFor(m => m.Answer, "Disagree")
Disagree
</label>
</div>
<div>
<label>
@Html.RadioButtonFor(m => m.Answer, "Not Sure")
Not Sure
</label>
</div>
Method 3
Finally, if you would like to get fancy, you can use an enum. Place the following in your controller:
public enum AnswerType {
Agree,
Disagree,
NotSure
}
Next, add the property to your model:
public AnswerType AnswerType { get; set; }
And then add the following to your view:
@Html.RadioButtonForEnum(m => m.AnswerType)
Hope this helps!
this will work Radio button for model
@using (Html.BeginForm())
{
foreach (var department in Model.Departments)
{
@Html.RadioButtonFor(m => m.SelectedDepartment, department.Id) @department.Name
}
<input type="submit" value="Submit" />
}
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