Your misunderstanding how radio buttons work. They are for binding one of many options to a single property, in the same way a dropdownlist works. Your code is generating radio buttons that bind to itself. And if you inspect the html you will see that it generates name="item.category_id"
which would not bind to your model anyway (that would only bind to a model containing a complex object named Item
which contained a property named category_id
).
Assuming you have a model for a Product
which contained a property for its Category
, and you wanted to assign one of the values of your category
table to the Category
property, then your view models would look like
public class ProductVM
{
[Required(ErrorMessage = "Please select a category")]
public int? Category { get; set; }
public IEnumerable<CategoryVM> CategoryOptions { get; set; }
}
public class CategoryVM
{
public int ID { get; set; }
public string Name { get; set; }
}
Note the use of a nullable property for Category
is explained in What does it mean for a property to be [Required] and nullable?
Then the controller methods (for a Create view) would look like
public ActionResult Create()
{
ProductVM model = new ProductVM();
ConfigureViewModel(model);
return View(model);
}
public ActionResult Create(ProductVM model)
{
if (!ModelState.IsValid())
{
ConfigureViewModel(model);
return View(model);
}
.... // Initialize your Product data model, set its properties based on the view model
// Save and redirect
}
private void ConfigureViewModel(ProductVM model)
{
model.CategoryOptions = db.categories.Select(x => new CategoryVM
{
ID = x.category_id,
Name = x.category_desc
});
}
Then the view would be
@model ProductVM
....
@using (Html.BeginForm())
{
@Html.DisplayNameFor(m => m.Category)
foreach(var category in Model.CategoryOptions)
{
<label>
@Html.RadioButtonFor(m => m.Category, category.ID, new { id = "" })
<span>@category.Name</span>
</label>
}
@Html.ValidationMessageFor(m => m.Category)
<input type="submit" .... />
}
Note that the new { id = "" }
is removing the id
attribute which would otherwise be invalid html because of duplicates.