gpt4 book ai didi

c# - 从 asp.net mvc 中的数据库表填充单选按钮列表

转载 作者:太空狗 更新时间:2023-10-29 23:21:28 24 4
gpt4 key购买 nike

enter image description here

我想创建一个像上面那样的表单,

还必须根据 UserGroups 表填充查看器用户组 enter image description here

public partial class UserGroup
{
public string UserGroup_ID { get; set; }
public string UserGroupNameEn { get; set; }
}

所以填充这个用户组并获取我创建新模型的填充数据(因此它可以应用于 View (第一个图像))

我遵循了这些 Stack overflow question 1question 2做这个

这是这个的 Controller 类

    [HttpGet]
public ActionResult ProductFields_Create()
{
var model = new ProductFields
{
LisGroups = GetUserGroupListEn()
};

return View(model);

}

public MultiSelectList GetUserGroupListEn()
{
return new MultiSelectList(db.UserGroup.ToList(), "UserGroup_ID", "UserGroupNameEn");
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ProductFields_Create(ProductFields product_fields)
{
...........
}

这是第一张图片的模型类

public class ProductFields
{
public string ProductFieldID { get; set; }
public string ProductFieldNameEn { get; set; }
public string ProductFieldNameAr { get; set; }
public string ProdcutFieldDiscriptionEn { get; set; }
public string ProductFieldDiscriptionAr { get; set; }

public List<UserGroup> LisGroups { get; set; }

[Required]
public string SelectedGroupID { get; set; }
}

上面 View 的viewpage

@model Project_Name.Models.ProductFields

@using (Html.BeginForm())
{

<fieldset>
<div class="form-horizontal">

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

.....

<div class="form-group">
<div>
@Html.ValidationMessageFor(x => x.SelectedGroupID)
foreach (var group in Model.LisGroups)
{
<div>
@Html.RadioButtonFor(x => x.SelectedGroupID, group.UserGroup_ID, new { id = "emp" + group.UserGroup_ID })
@Html.Label("emp" + group.UserGroup_ID, employee.Label)
</div>
}

</div>

</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>


</div>
</fieldset>
}

但在这里我遇到了红色波浪线的重大错误

The name 'group' does not exist in the current context

enter image description here

Cannot implicitly convert type 'System.Web.Mvc.MultiSelectList' to 'System.Collections.Generic.List'

enter image description here

最佳答案

你不需要 MultiSelectList (这是一个用于 ListBox()ListBoxFor() 方法的类)。而报错的原因是你的属性是List<UserGroup> LisGroups但是你试图分配 typeof MultiSelectList

将您的 GET 方法更改为

[HttpGet]
public ActionResult ProductFields_Create()
{
var model = new ProductFields
{
LisGroups = db.UserGroup.ToList();
};
return View(model);
}

旁注:属性可以是 public IEnumerable<UserGroup> LisGroups { get; set; }然后删除不必要的.ToList()

然后在 View 中

@foreach (var group in Model.LisGroups)
{
<div>
<label>
@Html.RadioButtonFor(x => x.SelectedGroupID, group.UserGroup_ID, new { id = "" })
<span>@group.UserGroupNameEn</span>
</label>
</div>
}

关于c# - 从 asp.net mvc 中的数据库表填充单选按钮列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33644854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com