I have a below model
public class category
{
[Key]
public long category_id { get; set; }
public string category_desc { get; set; }
public long? client_id { get; set; }
public long? display_sno { get; set; }
}
controller passing the model to view
public ActionResult category(long? client_id)
{
var category_type = db.category.Where(m => m.client_id == null).ToList();
if(client_id == 10)
{
category_type = db.category.Where(m => m.client_id == client_id).ToList();
}
return View(category_type);
}
In view populating the radion button
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.display_sno)<text>.</text>
@Html.RadioButtonFor(modelItem => item.category_id, item.category_id, new { id=item.category_id})@item.category_desc
}
post Method
public ActionResult Category(category g)
{
}
In post method g is coming as null.
What I am missing here?
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 namedItemwhich contained a property namedcategory_id).Assuming you have a model for a
Productwhich contained a property for itsCategory, and you wanted to assign one of the values of yourcategorytable to theCategoryproperty, then your view models would look likeNote the use of a nullable property for
Categoryis 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
Then the view would be
Note that the
new { id = "" }is removing theidattribute which would otherwise be invalid html because of duplicates.