【问题标题】:CheckBoxList using ASP.NET MVC 5CheckBoxList 使用 ASP.NET MVC 5
【发布时间】:2016-10-20 17:37:43
【问题描述】:

我无法理解如何从我的数据库中的设备表中检索数据到 CheckBoxList。

我相信我已经正确设置了模型、视图模型和数据库,但我只是不确定下一步该做什么。现在,我很想学习如何将数据从我的表中检索到 CheckBoxList。

客户模型

    public class Customer
{
    public int CustId { get; set; }
    public string CustDisplayName { get; set; }
    public string CustFirstName { get; set; }
    public string CustLastName { get; set; }
    public string CustCompanyName { get; set; }
    public string CustAddress { get; set; }
    public string CustPhoneNumber { get; set; }
    public string CustMobileNumber { get; set; }
    public string CustEmailAddress { get; set; }

    public int StId { get; set; }
    public State State { get; set; }
}

状态模型

    public class State
{
    public int StId { get; set; }
    public string StAbbr { get; set; }

    public List<Customer> Customers { get; set; }
}

设备型号

    public class Device
{
    public int DevId { get; set; }
    public string DevType { get; set; }
    public bool isChecked { get; set; }
}

客户设备模型

    public class CustomerDevice
{
    public int CustId { get; set; }
    public int DevId { get; set; }

    public Customer Customer { get; set; }
    public Device Device { get; set; }
}

客户视图模型

public class CustomerFormViewModel
{
    public int CustId { get; set; }

    [Required(ErrorMessage = "Enter Display Name")]
    [Display(Name = "Display Name")]
    [StringLength(100)]
    public string CustDisplayName { get; set; }

    [Display(Name = "First Name")]
    [StringLength(50)]
    public string CustFirstName { get; set; }

    [Display(Name = "Last Name")]
    [StringLength(50)]
    public string CustLastName { get; set; }

    [Display(Name = "Company Name")]
    [StringLength(50)]
    public string CustCompanyName { get; set; }

    [Display(Name = "Phone Number")]
    [DataType(DataType.PhoneNumber)]
    [StringLength(12)]
    public string CustPhoneNumber { get; set; }

    [Display(Name = "Mobile Number")]
    [DataType(DataType.PhoneNumber)]
    [StringLength(12)]
    public string CustMobileNumber { get; set; }

    [Display(Name = "Email Address")]
    [DataType(DataType.EmailAddress)]
    [StringLength(320)]
    public string CustEmailAddress { get; set; }

    [Required(ErrorMessage = "Enter Address")]
    [Display(Name = "Address")]
    [StringLength(100)]
    public string CustAddress { get; set; }

    [Required(ErrorMessage = "Select State")]
    [Display(Name = "State")]
    public int StId { get; set; }

    public IEnumerable<State> States { get; set; }
}

客户控制器

public class CustomerController : Controller
{
    private CoreWebAppContext _context;

    public CustomerController(CoreWebAppContext context)
    {
        _context = context;
    }


    // GET: /<controller>/
    public IActionResult Index()
    {
        return View(_context.Customers.ToList());
    }


    public ActionResult Create()
    {
        var states = _context.States.ToList();
        var viewModel = new CustomerFormViewModel
        {
            States = states
        };

        return View(viewModel);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(CustomerFormViewModel vm)
    {
        if (ModelState.IsValid)
        {
            var customer = new Customer();
            {
                customer.CustDisplayName = vm.CustDisplayName;
                customer.CustFirstName = vm.CustFirstName;
                customer.CustLastName = vm.CustLastName;
                customer.CustCompanyName = vm.CustCompanyName;
                customer.CustAddress = vm.CustAddress;
                customer.CustPhoneNumber = vm.CustPhoneNumber;
                customer.CustMobileNumber = vm.CustMobileNumber;
                customer.CustEmailAddress = vm.CustEmailAddress;
                customer.StId = vm.StId;
            }
            _context.Customers.Add(customer);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }

        else
        {
            vm.States = _context.States.ToList();
            return View(vm);
        }
    }


    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var customervm = new CustomerFormViewModel();
        {
            Customer customer = _context.Customers.SingleOrDefault(c => c.CustId == id);

            if (customer == null)
            {
                return NotFound();
            }

            customervm.CustId = customer.CustId;
            customervm.CustDisplayName = customer.CustDisplayName;
            customervm.CustFirstName = customer.CustFirstName;
            customervm.CustLastName = customer.CustLastName;
            customervm.CustCompanyName = customer.CustCompanyName;
            customervm.CustAddress = customer.CustAddress;
            customervm.CustPhoneNumber = customer.CustPhoneNumber;
            customervm.CustMobileNumber = customer.CustMobileNumber;
            customervm.CustEmailAddress = customer.CustEmailAddress;

            // Retrieve list of States
            var states = _context.States.ToList();
            customervm.States = states;

            // Set the selected state
            customervm.StId = customer.StId;
        }
        return View(customervm);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(CustomerFormViewModel vmEdit)
    {
        if (ModelState.IsValid)
        {
            Customer customer = _context.Customers.SingleOrDefault(c => c.CustId == vmEdit.CustId);

            if (customer == null)
            {
                return NotFound();
            }

            customer.CustDisplayName = vmEdit.CustDisplayName;
            customer.CustFirstName = vmEdit.CustFirstName;
            customer.CustLastName = vmEdit.CustLastName;
            customer.CustCompanyName = vmEdit.CustCompanyName;
            customer.CustAddress = vmEdit.CustAddress;
            customer.CustPhoneNumber = vmEdit.CustPhoneNumber;
            customer.CustMobileNumber = vmEdit.CustMobileNumber;
            customer.CustEmailAddress = vmEdit.CustEmailAddress;
            customer.StId = vmEdit.StId;

            _context.Entry(customer).State = EntityState.Modified;
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(vmEdit);
    }


}

创建视图

<div class="form-group">
    @Html.LabelFor(c => c.CustDisplayName)
    @Html.TextBoxFor(c => c.CustDisplayName, new { @class = "form-control" })
    @Html.ValidationMessageFor(c => c.CustDisplayName)
</div>

<div class="form-group">
    @Html.LabelFor(c => c.CustFirstName)
    @Html.TextBoxFor(c => c.CustFirstName, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(c => c.CustLastName)
    @Html.TextBoxFor(c => c.CustLastName, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(c => c.CustCompanyName)
    @Html.TextBoxFor(c => c.CustCompanyName, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(c => c.CustAddress)
    @Html.TextBoxFor(c => c.CustAddress, new { @class = "form-control" })
    @Html.ValidationMessageFor(c => c.CustAddress)
</div>

<div class="form-group">
    @Html.LabelFor(c => c.CustPhoneNumber)
    @Html.TextBoxFor(c => c.CustPhoneNumber, new { @class = "form-control" })
    @Html.ValidationMessageFor(c => c.CustPhoneNumber)
</div>

<div class="form-group">
    @Html.LabelFor(c => c.CustMobileNumber)
    @Html.TextBoxFor(c => c.CustMobileNumber, new { @class = "form-control" })
    @Html.ValidationMessageFor(c => c.CustMobileNumber)
</div>

<div class="form-group">
    @Html.LabelFor(c => c.CustEmailAddress)
    @Html.TextBoxFor(c => c.CustEmailAddress, new { @class = "form-control" })
    @Html.ValidationMessageFor(c => c.CustEmailAddress)
</div>

<div class="form-group">
    @Html.LabelFor(s => s.StId)
    @Html.DropDownListFor(s => s.StId, new SelectList(Model.States, "StId", "StAbbr"), "", new { @class = "form-control" })
    @Html.ValidationMessageFor(s => s.StId)
</div>

<div class="form-group">
    <button type="submit" class="btn btn-primary">Submit</button>
</div>

【问题讨论】:

  • 有没有办法在不使用编辑器模板的情况下将我的设备数据检索到 CheckBoxList?抱歉,对如何将设备数据检索到创建视图有点困惑。在我学习如何至少填充 CheckBoxList 之后,我将需要学习如何根据客户的 ID 将选定的复选框值分配给客户。

标签: c# asp.net asp.net-mvc


【解决方案1】:

创建另一个名为 IndexViewModel 的 ViewModel 类并将其放在上面:

public class IndexViewModel
{
    public List<Customer> Customers { get; set; }
    public List<Device> Devices { get; set; }
}

这是您的控制器操作。而是返回新的 IndexViewModel:

// GET: /<controller>/
public IActionResult Index()
{
    return View(_context.Customers.ToList());
}

// GET: /<controller>/
public IActionResult Index()
{
    var model = new IndexViewModel();
    model.Customers = _context.Customers.ToList();
    model.Devices = _context.Devices.ToList();

    return View(model);
}

在您看来,只需迭代设备列表:

@{
    for(int i = 0; i < Model.Devices.Count(); i++)
    {
        var checkboxAttributes = Model.Devices[i].isChecked == true ?
            (object) new { @class = "checkbox", @checked = "checked" } :
            (object) new { @class = "checkbox" };

        @Html.CheckBoxFor(model => model.Devices[i].DevType, checkboxAttributes)
        @Html.LabelFor(model => model.Devices[i].DevType, new { @class = "label" })
    }
}

更新 1

我对上一个很抱歉,但这是正确的版本:它使用引导样式作为复选框:

@{
    for (int i = 0; i < Model.Devices.Count(); i++)
    {
        <div class="checkbox">
            <label>
                @Html.HiddenFor(model => model.Devices[i].DevId)
                @Html.CheckBoxFor(model => model.Devices[i].isChecked)
                @Html.DisplayFor(model => model.Devices[i].DevType)
                @Html.HiddenFor(model => model.Devices[i].DevType)
            </label>
        </div>
    }
}

【讨论】:

  • @Christian,我在下面的代码行@Html.CheckBoxFor(model =&gt; model.Devices[i].DevType, checkboxAttributes) 上有一条红线。错误消息说**无法隐式转换类型“字符串”或“布尔”无法将 lambda 表达式转换为预期的委托类型,因为块中的某些返回类型不能隐式转换为委托返回类型。**
  • 是的,这里有错误,看看修改后的代码。
  • 我的 Device 模型在我的数据库中的 Device 表中具有相同的 3 列。我需要设备表中的 isChecked 列吗?如果我从我的设备表中删除列 isChecked 我会在此行下面收到以下错误消息var devices = _context.Devices.ToList(); 错误消息显示 'System.Data.SqlClient.SqlException' 类型的异常发生在 Microsoft.EntityFrameworkCore.dll 中,但未在用户代码中处理。附加信息:列名“isChecked”无效。
【解决方案2】:

你可以使用这样的东西,这样你就可以将它重复用于不同的模型。

CheckboxViewModel:

public class CheckboxViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public bool Checked { get; set; }
}

扩展方法:

public static IEnumerable<CheckboxViewModel> CreateCheckboxList<T>(this List<T> entities, Func<T, object> value, Func<T, object> text, Func<T, bool> isChecked)
    {
        return entities.Select(x => new CheckboxViewModel
        {
            Id = (int)value(x),
            Name = text(x).ToString(),
            Checked = isChecked(x)
        });
    }

使用示例:

result = devices.CreateCheckboxList(x => x.Id, x => x.Name, x => selectedDevices.Contains(x.Id)).ToList();

@for (var deviceIndex = 0; deviceIndex < Model.Devices.Count(); deviceIndex ++)
                            {
                                <div class="form-group">
                                    <div class="checkbox checkbox-primary">
                                        @Html.HiddenFor(model => model.Devices[deviceIndex ].Id)
                                        @Html.CheckBoxFor(model => model.Devices[deviceIndex ].Checked)
                                        @Html.LabelFor(model => model.Devices[deviceIndex ].Checked, Model.Devices[deviceIndex ].Name)
                                    </div>
                                </div>
                            }

【讨论】:

  • 不错的答案。我遇到的唯一问题是扩展中的 Id 演员表。改用 int.Parse。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
相关资源
最近更新 更多