【问题标题】:CheckBoxList does not update the modelCheckBoxList 不更新模型
【发布时间】:2011-12-29 00:14:40
【问题描述】:

我定义了一个 Person 实体:

public partial class Person
{
 public string persID { get; set; }
 public string last_name { get; set; }
 public string driving_licence { get; set; }
}

驾驶执照如下:

public class DrivingLicence
    { 
        public string drivingLicenceValue { get; set; }
        public string drivingLicenceText { get; set; }

        public DrivingLicence(string paValue, string paText)
        {
            drivingLicenceValue = paValue;
            drivingLicenceText = paText;
        }
    }

有一个定义了这个函数的存储库:

public List<DrivingLicence> GetAll()
{
        try
        {
            var drivingLicenceList = new List<DrivingLicence>();

            DrivingLicence oneDrivingLicence = new DrivingLicence("A", "A");
            drivingLicenceList.Add(oneDrivingLicence );

            oneDrivingLicence = new DrivingLicence("B", "B");
            drivingLicenceList.Add(oneDrivingLicence );


            oneDrivingLicence = new DrivingLicence("C", "C");
            drivingLicenceList.Add(oneDrivingLicence );

            oneDrivingLicence = new DrivingLicence("D", "D");
            drivingLicenceList.Add(oneDrivingLicence );

            return drivingLicenceList;
        }
        catch (Exception)
        {
            throw new Exception("An error occured. Failed to Get the list.");
        }
    }

现在:我希望将驾驶执照显示为 CheckBoxList 并且在提交时我希望此人获得已检查的驾驶执照类别,例如:选择“A”和“C”类别,生成的 person.driving_licence 必须是“交流”。

问题是这并没有发生,人已创建,但driving_licence 属性为空。我注意到复选框名称与相应属性(Person.driving_licence)的名称相同。

这是当前代码中的错误吗?或者我应该修改 Person 实体? 谢谢你的建议。

这是视图模型:

public class PersonFormViewModel
{
    // Properties
    public Person person { get; set; }
    public SelectList DrivingLicenceList { get; set; }
    public string ActionToPerform { get; set; }


    public PersonFormViewModel() { }

    // Constructor
    public PersonFormViewModel(Person pPerson, SelectList pDrivingLicenceList)
    {
        person= pPerson;
        DrivingLicenceList = pDrivingLicenceList;
        if (String.IsNullOrEmpty(person.persID))
        {
            ActionToPerform = "Create";
        }
        else
        {
            ActionToPerform = "Edit";
        }
    }
}

控制器:

    //
    // GET: /Person/Create
    [Authorize]
    public ActionResult Create()
    {
        Person person = new Person();
        SelectList drvLicenceList = new SelectList(drvLicenceRepository.GetAll(), "drivingLicenceValue", "drivingLicenceText");
        return View("Create", new PersonFormViewModel(person, drvLicenceList));
    }

    //
    // POST: /Person/Create

    [HttpPost, Authorize]
    public ActionResult Create(PersonFormViewModel model)
    {
         Person person = model.person;
         SelectList drvLicenceList = new SelectList(drvLicenceRepository.GetAll(), "drivingLicenceValue", "drivingLicenceText");

        if (ModelState.IsValid)
        {
            try
            {
                db.Entry(person).State = EntityState.Added;
                db.SaveChanges();
                return RedirectToAction("Details");
            }
            catch (...)
            {
                ...
            }
        }
        return View("Create", new PersonFormViewModel(person, drvLicenceList));
    }

还有观点:

@model MyApp.ViewModels.PersonFormViewModel
@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm())
{

    @Html.ValidationSummary(false, "Errors occured.")
    <fieldset>
        <legend>Fill in your details</legend>
        @Html.LabelFor(model => model.person.last_name)
        @Html.TextBoxFor(model => model.person.last_name)
        @Html.ValidationMessageFor(model => model.person.last_name, "*")
        @Html.HiddenFor(model => model.person.persID)

        @foreach (var ctg in (Model.DrivingLicenceList))
         {
             <input type="checkbox" name="driving_licence" value=ctg.value />@ctg.Text
         }
        <input type="submit" value="Sauvegarder" class="submit" />
    </fieldset>
}

【问题讨论】:

    标签: asp.net-mvc-3 checkboxlist


    【解决方案1】:

    我将使用集合属性来存储选定的驾驶执照类别(可以选择多个复选框 => 集合):

    public partial class Person
    {
        public string persID { get; set; }
        public string last_name { get; set; }
        public string[] driving_licence { get; set; }
    }
    

    然后您需要修复复选框的名称以使其正确绑定:

    @foreach (var ctg in Model.DrivingLicenceList)
    {
        <input type="checkbox" name="person.driving_licence" value="@ctg.Value" />
        @ctg.Text
    }
    

    如果您想保留选定的值,则需要相应地设置选中的属性:

    @foreach (var ctg in Model.DrivingLicenceList)
    {
        <input type="checkbox" name="person.driving_licence" value="@ctg.Value" @((Model.person.driving_licence ?? Enumerable.Empty<string>()).Contains(ctg.Value) ? "checked=\"checked\"" : "") />
        @ctg.Text
    }
    

    话虽如此,我们现在有了一个可行的解决方案,但它远非我会满足于并停在这里的任何事情。从现在开始,我们可以开始重构这个烂摊子以符合 C# 命名约定(属性名称以大写字母开头,...),引入真实视图模型(不引用域模型),自定义 HTML 助手生成此复选框列表以避免在视图和硬编码复选框中写入循环,...

    【讨论】:

    • 谢谢达林,您的回答一如既往地很有帮助。我现在必须休息一下,深入研究如何为 CheckBoxList 编写帮助程序以及如何重构我的代码。谢谢你的详细回答。
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多