如何从mvc中的radiobuttonfor获取唯一id

时间:2017-11-16 05:21:15

标签: asp.net-mvc asp.net-mvc-4 radiobuttonfor

我有一个以下型号

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; }
}

控制器将模型传递给视图

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);
}

在视图中填充radion按钮

@foreach (var item in Model)                                                 
{ 
    @Html.DisplayFor(modelItem => item.display_sno)<text>.</text> &nbsp;
    @Html.RadioButtonFor(modelItem => item.category_id, item.category_id, new { id=item.category_id})@item.category_desc
}

发布方法

public ActionResult Category(category g)
{

}

帖子方法g即将发布为null。 我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您误解了单选按钮的工作原理。它们用于将多个选项中的一个绑定到单个属性,与下拉列表的工作方式相同。您的代码正在生成绑定到自身的单选按钮。如果您检查html,您将看到它生成name="item.category_id",它无论如何都不会绑定到您的模型(只会绑定到包含名为Item的复杂对象的模型,该对象包含名为{{的属性1}})。

假设您有category_id的模型,其中包含Product的属性,并且您希望将Category表的其中一个值分配给category }属性,那么你的视图模型看起来像

Category

请注意What does it mean for a property to be [Required] and nullable?

中解释了使用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; } } 的可空属性

然后控制器方法(对于Create视图)看起来像

Category

然后视图将是

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
    });
}

请注意,@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" .... /> } 正在移除new { id = "" }属性,否则该属性因重复而无效。