Input type checkbox with MVC razor - asp.net-mvc

Why is the value of my checkbox not passed to my ViewModel?
My View (I omitted input tags not relevant for this post):
#model Pro.WebUI.ViewModels.UserViewModel
#using (Html.BeginForm("ManageUsers", "Administration", FormMethod.Post,
new { id = "request-form", #class = "form-horizontal" }))
{
<div class="form-group">
<label for="inputAuthorize" class="col-lg-2 control-label">Authorize</label>
<div class="col-lg-8">
<input type="checkbox" id="Authorized" name="Authorized" value="#Model.Authorized" />
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<br /><br />
<button type="submit" class="btn btn-primary">Submit Request</button>
</div>
</div>
}
My ViewModel:
public class UserViewModel
{
[Key]
public string UserID { get; private set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Authorized { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Notes { get; set; }
}
My Controller:
[HttpPost]
public ActionResult ManageUsers(UserViewModel model)
{
if (ModelState.IsValid)
{
ProcurementUser obj = new ProcurementUser();
obj.UserName = model.Email;
obj.FirstName = model.FirstName;
obj.LastName = model.LastName;
obj.Email = model.Email;
obj.Phone = model.Phone;
obj.Authorized = model.Authorized;
UserRepository.SaveUser(obj);
//success message
}
return View(model);
}
I did not include all input tags but when I step through the code without the checkbox, all values are passed. I looked at other checkbox questions on SOF but they mostly use the #Html.Checkbox or #Html.CheckboxFor. I would like to just use input type="checkbox"

If we need to use <input> filed instead of #Html.CheckboxFor, we can use "checked=\"checked\"" syntax as in this code:
<input type="checkbox" id="Authorized" name="Authorized" value="true" #(Model.Authorized ? "checked=\"checked\"" : "") />

As has been hinted at in the comments the issue you're having is that you're not really creating your checkbox correctly:
Assuming your model has Authorized = true your mark-up would be:
<input type="checkbox" id="Authorized" name="Authorized" value="true" />
Similarly the false state would result in:
<input type="checkbox" id="Authorized" name="Authorized" value="false" />
But these aren't "checked" checkboxes - they're still "unchecked", and need the checked attribute setting:
<input type="checkbox" id="Authorized" name="Authorized" value="true" checked />
As Stephen points out - an unchecked checkbox will not send any data back to the server so that you don't get confused about which options where selected.
Finally, as has also been noted, your <label> element is for an non-existent field looking for inputAuthorize instead of Authorized.
All of these issues would be taken care of for you if you were to use the #Html.CheckboxFor and #Html.LabelFor helper classes.

Related

Blog Comments MVC simple Creating new comments

I have problems getting my blog create comments working it works fine when I edit in the db putting the relation id in but I cannot get it when I use the form.
Error is here: Blogposts = id
public ActionResult BlogPost(int Id)
{
var _getSpecificBlogPost = db.Blogposts.Where(m => m.Id == Id).ToList();
return View(_getSpecificBlogPost);
}
[HttpPost]
public ActionResult BlogComment_Create(string name, string bodytext, string id )
{
BlogComment model = new BlogComment { Name = name, BodyText = bodytext, Blogposts = id};
db.BlogComments.Add(model);
db.SaveChanges();
return Redirect(Request.UrlReferrer.PathAndQuery);
}
In BlogComment I have: public virtual Blogpost Blogposts { get; set; }
In BlogPosts I have: public virtual ICollection<BlogComment> BlogComments { get; set; }
<form method="post" id="form-variant-create" action="#Url.Action("BlogComment_Create", "Blog")" role="form">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Name" />
<br />
<textarea name="bodytext" class="form-control" rows="3" placeholder="Message"></textarea>
<input type="text" class="hidden" name="id" value="#foreach(var item in Model){#item.Id}" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
BlogPosts is from BlogPost type. you need to create a property for your BlogPostId as ForeignKey.
public virtual int BlogPostId{get;set;}
Insert this line into your CommentModel. and then reffer to this instead of BlogPosts.
and edit your BlogPosts Property too.
[ForeignKey("BlogPostId")]
public virtual Blogpost Blogposts { get; set; }

How get values into a select box from sql server

Can anyone help me to populate a select box with values from sql server. I'm using MVC ASP.NET, I have a form, that is from a table X, one of it columns it's called Location and brings the city where it's from, but i have all the cities in another table Y, and want to insert the select inside that form. How should i enter the code inside the model/controller.
Here is how i set the form for table X:
Model:
public int Insertar(Inmueble inmueble)
{
SqlConnection conexion = new SqlConnection("Data Source=USUARIO-PC\\SQLEXPRESS;Integrated Security=True;Initial Catalog=jaera;");
conexion.Open();
SqlCommand comando = conexion.CreateCommand();
comando.CommandText = "insert into Inmuebles (Titulo, Descripcion, Ambientes, Precio, Localidad, Tags, Usuario)" +
"output inserted.Id values (#Titulo, #Descripcion, #Ambientes, #Precio, #Localidad, #Tags, #Usuario)";
comando.Parameters.AddWithValue("#Titulo", inmueble.Titulo);
comando.Parameters.AddWithValue("#Descripcion", inmueble.Descripcion);
comando.Parameters.AddWithValue("#Ambientes", inmueble.Ambientes);
comando.Parameters.AddWithValue("#Precio", inmueble.Precio);
comando.Parameters.AddWithValue("#Localidad", inmueble.Localidad);
comando.Parameters.AddWithValue("#Tags", inmueble.Tags);
comando.Parameters.AddWithValue("#Usuario", inmueble.Usuario);
int nuevoId = (int)comando.ExecuteScalar();
inmueble.Id = nuevoId;
conexion.Close();
return nuevoId;
}
This is my controller:
[HttpPost]
public ActionResult Create(FormCollection formulario)
{
string Titulo = formulario["Titulo"];
string Descripcion = formulario["Descripcion"];
int Precio = Convert.ToInt32(formulario["Precio"]);
int Ambientes = Convert.ToInt32(formulario["Ambientes"]);
int Localidad = Convert.ToInt32(formulario["Localidad"]);
string Usuario = formulario["Usuario"];
string Tags = formulario["Tags"];
Inmueble inmueble = new Inmueble();
inmueble.Titulo = Titulo;
inmueble.Localidad = Localidad;
inmueble.Precio = Precio;
inmueble.Ambientes = Ambientes;
inmueble.Usuario = Usuario;
inmueble.Descripcion = Descripcion;
inmueble.Tags = Tags;
InmueblesManager managerInmuebles = new InmueblesManager();
int idInsertado = managerInmuebles.Insertar(inmueble);
if (Request.Files.Count > 0 &&
Request.Files[0].ContentLength > 0) //para validar que vino el archivo
{
string rutaFinal = Server.MapPath("~/Content/imagenes/inmuebles/" + idInsertado + ".jpg");
Request.Files[0].SaveAs(rutaFinal);
}
return RedirectToAction("Index", "Home");
}
And this is how it looks at html code the form:
<form action="#Url.Action("Create", "Inmuebles")" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="Titulo">Titulo</label>
<input id="Titulo" name="Titulo" type="text" placeholder="Titulo" />
</div>
<div class="form-group">
<label for="Localidad">Localidad</label>
<input id="Localidad" name="Localidad" type="text" placeholder="Localidad del Inmueble" />
</div>
<div class="form-group">
<label for="Descripcion">Descripcion</label>
<textarea id="Descripcion" name="Descripcion" placeholder="Ingresa aqui la descripcion"></textarea>
</div>
<div class="form-group">
<label for="Precio">Precio</label>
<input type="number" id="Precio" name="Precio" />
</div>
<div class="form-group">
<label for="Ambientes">Ambientes</label>
<input type="number" id="Ambientes" name="Ambientes" />
</div>
<div class="form-group">
<label for="Tags">Tags</label>
<input id="Tags" name="Tags" type="text" placeholder="Tags para una busqueda mas rapida" />
</div>
<div>
<input type="hidden" value="#(((ja_era.Models.Usuario)Session["usuario"]).NombreDeUsuario)" name="Usuario" />
</div>
<div class="form-group">
<label for="imagen">Imagen</label>
<input id="imagen" name="imagen" type="file" />
</div>
<input type="submit" value="Guardar" />
You haven't even attempted anything, which is kind of a no-no around these parts. I will give you a bit of general guidance, though. First, use a view model to pass data to/from the view. You should pretty much never take a FormCollection.
public class InmuebleViewModel
{
public string Titulo { get; set; }
public int Localidad { get; set; }
public int Precio { get; set; }
public int Ambientes { get; set; }
public string Usuario { get; set; }
public string Descripcion { get; set; }
public string Tags { get; set; }
}
Then, your get action should pass this to your view:
public ActionResult Create()
{
var model = new InmuebleViewModel();
return View(model);
}
Your view should use this model and utilize the HTML helpers to generate your inputs:
#model Namespace.To.InmuebleViewModel
...
<div class="form-group">
#Html.LabelFor(m => m.Titulo)
#Html.EditorFor(m => m.Titulo, new { htmlAttributes = new { placeholder = "Titulo" } })
</div>
...
Finally, your post action should take this view model as a param:
[HttpPost]
public ActionResult Create(InmuebleViewModel model)
{
...
}
That's all just standard MVC best practice stuff. However, using the view model also gives you the ability to have a select list on it:
public IEnumerable<SelectListItem> FooOptions { get; set; }
Which you can then use in your view:
#Html.DropDownListFor(m => m.Foo, Model.FooOptions)
You just need to populate that property in both your get and post actions. For that, I recommend adding a protected method to your controller that both can call to keep it dry:
protected void PopulateFooOptions(InmeubleViewModel model)
{
// retrieve you options from the database, selected into an enumerable of `SelectListItem`
model.FooOptions = options;
}
Then, both your get and post Create actions call this before returning the view:
PopulateFooOptions(model);
return View(model);

Passing values of checkboxes from View to Controller

I have a view with a number of checkboxes in it. I want to be able to pass the values of the checkboxes to the controller, then output a list of the OfficeNames that have been ticked. I am not sure how to pass the values of multiple checkboxes back to the controller, or how to output the OfficeNames based on which boxes have been ticked
View:
<p>
#using (Html.BeginForm())
{
<p>
Start Date: #Html.TextBox("StartDate") <br />
<br />
End Date: #Html.TextBox("EndDate") <br />
<br />
<input type="submit" value="Filter" />
</p>
}
<p>
#foreach (var item in Model.BettingOffices)
{
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="selectedShops" value="#item.OfficeName">
}
</p>
Controller:
public class DailyReportController : Controller
{
private RiskEntities _db = new RiskEntities();
// GET: /DailyReport/
public ActionResult Index(DateTime? startDate, DateTime? endDate)
{
if (startDate == null || endDate == null)
{
var dailyReportModelBlank = new DailyReportModel();
dailyReportModelBlank.BettingOffices = (from bo in _db.BettingOffices orderby bo.OfficeName select bo ).ToList();
//dailyReportModelBlank.DailyReports.Add(new DailyReport());
return View(dailyReportModelBlank);
}
var endDateToUse = (DateTime) endDate;
endDateToUse = endDateToUse.AddDays(+1);
var dailyReportModel = new DailyReportModel
{
DailyReports = (from dr in _db.DailyReports
where dr.DailyReportDate >= startDate
&& dr.DailyReportDate <= endDateToUse
select dr).ToList(),
BettingOffices = (from bo in _db.BettingOffices select bo).ToList()
};
return View(dailyReportModel);
}
Model:
public class DailyReportModel
{
private List<DailyReport> _dailyReports = new List<DailyReport>();
private List<BettingOffice> _bettingOffices = new List<BettingOffice>();
public List<DailyReport> DailyReports
{
get { return _dailyReports; }
set { _dailyReports = value; }
}
public List<BettingOffice> BettingOffices
{
get { return _bettingOffices; }
set { _bettingOffices = value; }
}
}
BettingOffice Class:
public partial class BettingOffice
{
public int BettingOfficeID { get; set; }
public string OfficeName { get; set; }
public string OfficeCode { get; set; }
public string IpAddress { get; set; }
public Nullable<bool> SupportOnly { get; set; }
public Nullable<int> SisSrNumer { get; set; }
public Nullable<bool> Local { get; set; }
public string Server { get; set; }
}
try this :
<p>
#using (Html.BeginForm())
{
<p>
Start Date: #Html.TextBox("StartDate")
<br />
<br />
End Date: #Html.TextBox("EndDate")
<br />
<br />
<input type="submit" value="Filter" />
</p>
}
</p>
<p>
#foreach (var item in Model.BettingOffices)
{
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="bettingOfficeIDs" value="#item.BettingOfficeID">
}
</p>
And in your Action you can get the selected office ids in bettingOfficeIDs variable:
public ActionResult YourActionName(int[] bettingOfficeIDs)
Few things that need to change here.
If you want values to be passed to action method they need to be within form not outside
For MVT to 'understand' checkbox values as array (or more complex object) you need to work with their html name attribute.
I will do demonstration application below that should help you understand how it works:
CsHtml: Notice that you need to add value attribute to checkboxes to be able to read their values, checkbox gets true only when checkbox is ticked and value is true, hence the javascript. You can add as many of complex object properties as hidden fields as long as you give them names that match to the object property names in viewModel. In this case I am only passing BettingOfficeID
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).on("click", "[type='checkbox']", function(e) {
if (this.checked) {
$(this).attr("value", "true");
} else {
$(this).attr("value","false");}
});
<p>
#using (Html.BeginForm())
{
<p>
Start Date: #Html.TextBox("StartDate") <br />
<br />
End Date: #Html.TextBox("EndDate") <br />
<br />
</p>
<p>
<input type="checkbox" name="BettingOffices[0].Selected" value="true">
<input type="hidden" name="BettingOffices[0].BettingOfficeID" value="1">
<input type="checkbox" name="BettingOffices[1].Selected" value="false">
<input type="hidden" name="BettingOffices[1].BettingOfficeID" value="2">
<input type="checkbox" name="BettingOffices[2].Selected" value="true">
<input type="hidden" name="BettingOffices[2].BettingOfficeID" value="3">
<input type="checkbox" name="BettingOffices[3].Selected" value="false">
<input type="hidden" name="BettingOffices[3].BettingOfficeID" value="4">
<input type="checkbox" name="BettingOffices[4].Selected" value="true">
<input type="hidden" name="BettingOffices[4].BettingOfficeID" value="5">
</p>
<input type="submit" value="submit"/>
}
Post Action method to add to controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(BettingViewModel viewModel)
{
return null;
}
BettingViewModel: I have added Selected property to BettingOffice class.
public class BettingViewModel
{
public string StartDate { get; set; }
public string EndDate { get; set; }
public List<BettingOffice> BettingOffices { get; set; }
}
public class BettingOffice
{
public bool Selected { get; set; }
public int BettingOfficeID { get; set; }
public string OfficeName { get; set; }
public string OfficeCode { get; set; }
public string IpAddress { get; set; }
public Nullable<bool> SupportOnly { get; set; }
public Nullable<int> SisSrNumer { get; set; }
public Nullable<bool> Local { get; set; }
public string Server { get; set; }
}
Hope this saves you some time.
View:
#using (Html.BeginForm("Createuser", "User", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<div class="form-group">
#Html.LabelFor(m => m.city, new { #class = "col-md-2 control-label" })
</div>
<div class="col-md-10">
<table>
<tr>
<td><input type="checkbox" name="city" value="Pune" id="1" />Pune</td>
<td><input type="checkbox" name="city" value="Banglore" id="2" />Banglore</td>
<td><input type="checkbox" name="city" value="Mumbai" id="3" />Mumbai</td>
</tr>
</table>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Create" />
</div>
</div>
}
[HttpPost]
public ActionResult Createuser(user user, string [] city)
{
var UserInfo = new user
{ Email =user.Email,Password=user.Password,Firstname=user.Firstname };
return View();
}
1. First of all, you are generating checkboxes with same name. So how you will be able to retrieve them on server end separately?
So declare some counter that gets incremented and name checkboxes uniquely.
#foreach (var item in Model.BettingOffices)
{
int counter=1;
var checkboxName = "selectedShops" + counter;
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="#checkboxName" value="#item.OfficeName">
counter++;
}
2. Now on submission of Form in your controller, get checkboxes as -
//Loop through the request.forms
for (var i = 0; i <= Request.Form.Count; i++)
{
var checkboxValue = Request.Form["selectedShops[" + i + "]"];
// Do whatever you want to with this checkbox value
}
For ticked values, you will probably get True value. Debug the retrieved value to write further code accordingly.
Try the following
your View is:
#foreach (var item in Model.BettingOffices)
{
<label>#Html.DisplayFor(modelItem => item.OfficeName)</label>
<input type="checkbox" name="selectedShops" value="#item.OfficeName">
}
Controller
[HttpPost]
public ActionResult Index(FormCollection collection)
{
if(!string.IsNullOrEmpty(collection["selectedShops"]))
{
string strSelectedShops = collection["selectedShops"];
}
}
Hi you can get the selected checkbox value using the bellow code it seem working fine fore me,
<script>
$(document).ready(function()
{
$("input[type=checkbox]").click(function()
{
var categoryVals = [];
categoryVals.push('');
$('#Category_category :checked').each(function() {
categoryVals.push($(this).val());
});
$.ajax({
type:"POST",
url:"<?php echo $this->createUrl('ads/searchresult'); ?>", //url of the action page
data:{'category': categoryVals},
success : function(response){
//code to do somethng if its success
}
});
}
}
</script>

How to input multiple types with one controller action MVC5

I'm really new to MVC and I am trying to be clever..
I have one View that displays one question but offers various methods of responding;
#using Microsoft.AspNet.Identity
#model Template.Models.Question
#{
ViewBag.Title = "View question";
var qtype = Model.QuestionTypeId;
ViewBag.Number = Model.Id - 7;
Html.BeginForm("ViewQuestion", "Question", FormMethod.Post, new { #class = "form-horizontal", role = "form" });
}
<div>
<h4>Question ##ViewBag.Number</h4>
<hr />
<h1> #Model.Question1</h1>
</div>
#Html.AntiForgeryToken()
<div class="form-group">
#switch (qtype)
{
case 1:
// Textbox
#Html.TextArea("Answer", new { #class = "form-control", rows = "4", col = "5" });
break;
case 2:
// Dropdown
<select class="form-control" id="Answer">
#foreach (var item in Model.QuestionOptions.OrderBy(o => o.QuestionOptionRanking))
{
<option value="#item.QuestionOption1">#item.QuestionOption1</option>
}
</select>
break;
case 3:
// Checkbox
<div class="checkbox">
#foreach (var item in Model.QuestionOptions.OrderBy(o=> o.QuestionOptionRanking))
{
<input type="checkbox" name="Answer" value="#item.QuestionOption1" /> #item.QuestionOption1 <br />
}
</div>
break;
case 4:
// Radio buttons
foreach (var item in Model.QuestionOptions.OrderBy(o => o.QuestionOptionRanking))
{
<div class="radio">
<label>
<input type="radio" name="Answer" value="#item.QuestionOption1" />
#item.QuestionOption1
</label>
</div>
}
break;
}
</div>
<input type="hidden" name="QuestionId" value="#Model.Id" />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Answer" />
</div>
</div>
My ViewModel;
public class ResponseViewModel
{
[Required]
public string UserId { get; set; }
[Required]
public int QuestionId { get; set; }
[Required(ErrorMessage = "Please answer the question before submitting")]
public string Answer { get; set; }
[Required]
public string Source { get; set; }
[Required]
public string Status { get; set; }
[Required]
public System.DateTime DateStamp { get; set; }
public Nullable<int> Duplicate { get; set; }
public virtual Question Questions { get; set; }
public object SelectedValue { get; set; }
public virtual ICollection<QuestionOption> QuestionOptions { get; set; }
}
And finally my action;
[HttpPost]
public ActionResult ViewQuestion([Bind(Include = "QuestionId, Answer")] ResponseViewModel responseViewModel)
{
//var optionSelected = responseViewModel.Answer;
//if (optionSelected == null)
//{
// optionSelected = responseViewModel.Answer.SelectedValue();
//}
Response re = new Models.Response();
re.Answer = responseViewModel.Answer;
if (re.Answer == null)
{
re.Answer = "Work in progress!";
// re.Answer = responseViewModel.SelectedValue();
// re.Answer = int.Parse(SelectList["Question.QuestionOption1"]);
}
re.UserId = User.Identity.GetUserId();
re.QuestionId = responseViewModel.QuestionId;
re.Source = "Web";
re.Status = "New";
re.DateStamp = System.DateTime.Now;
db.Responses.Add(re);
db.SaveChanges();
return RedirectToAction("ViewQuestion");
}
If you examine the view you will notice an "Answer" can be a textbox, checkbox, radio buttons or dropdown. Everything works fine on display, some questions have dropdownlists, others radio button, etc. Its the posting that's got me stumped. If you notice I have not used HTML Helpers, but old fashion HTML as I kept getting errors that the types I've mentioned did not exist in my helpers.
Post works fine if its a text box, but if you look at my controller action you will see a few commented out attempts to also catch the values if it is one of the other controllers..
I thought I was being clever with my cases, but now I can't seem to write any code that will capture the selected, or checked options.
Any advice would be great!
I can think of one possibility off the top of my head. In MVC, you can have more than one form on a page. Instead of wrapping all of your cases in one form, make each case it's own form with it's own submit button, and have an action method for each one.
EDIT
Also in looking at your code, you're going to have a problem with the checkboxes because your Answer property is a String and if more than one checkbox is checked you're going to get an array

Why does the selected radio button at runtime differ from my programmatic setup?

I have data model classes as follows:
public class QuizItem
{
public int QuizItemId { get; set; }
public string Question { get; set; }
public IEnumerable<Choice> Choices { get; set; }
}
and
public class Choice
{
public int ChoiceId { get; set; }
public string Description { get; set; }
public bool IsCorrect { get; set; }
}
I made a setup in a controller action as follows:
public class HomeController : Controller
{
public ActionResult Index()
{
IEnumerable<Choice> choices = new Choice[]
{
new Choice{ChoiceId=1,Description="Black",IsCorrect=true},
new Choice{ChoiceId=2,Description="Red",IsCorrect=false},
new Choice{ChoiceId=3,Description="Yellow",IsCorrect=false}
};
QuizItem qi = new QuizItem { QuizItemId = 1,
Question = "What color is your hair?",
Choices = choices };
return View(qi);
}
The last, here is my view:
#model MvcApplication1.Models.QuizItem
#{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<fieldset>
<legend>QuizItem</legend>
<div class="display-label">
Question</div>
<div class="display-field">#Model.Question</div>
#foreach (var x in Model.Choices)
{
<text>#Html.RadioButtonFor(y => Model.QuizItemId, x.Description, new { #checked = x.IsCorrect })
#x.Description<br /></text>
}
</fieldset>
At runtime, the selected option should be Black. But Yellow gets selected. How to resolve this issue?
You need to set the #checked attribute to the string "checked", not true/false.
new { #checked = x.IsCorrect ? "checked" : string.Empty }
JK is right at the same time he is wrong.
The checked attribute should really be used with the "checked" value, the correct and valid W3C html markup for a checked radio is:
<input type="radion" name="something" value="1" checked="checked">
But, when you output this:
<input type="radion" name="something" value="1" checked="">
The browser still renders it as a checked radio. Your own solution is the best so far.
I find that the radio button helper is too much trouble to get to work correctly.
You are best off with writing the raw HTML for the the radio buttons yourself. This is especially true when you have multiple options:
<input type="radio" id="ques1_choice1" name="quizQuestion1" value="1" #(x.IsCorrect ? "checked=\"checked\"" : null) />
<input type="radio" id="ques1_choice2" name="quizQuestion1" value="2" #(x.IsCorrect ? "checked=\"checked\"" : null) />
I found the solution as follows:
<fieldset>
<legend>#Model.Question</legend>
#foreach (var x in Model.Choices)
{
<text>#Html.RadioButton(Model.QuizItemId.ToString(), x.Description, x.IsCorrect)
#x.Description<br /></text>
}
</fieldset>

Resources