CheckBoxList不会更新模型

时间:2011-12-29 00:14:40

标签: asp.net-mvc-3 checkboxlist

我定义了一个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必须是“AC”。

问题是这不会发生,创建人员但drive_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>
}

1 个答案:

答案 0 :(得分:1)

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

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
}

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

@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帮助程序将生成此复选框列表以避免在视图和硬编码复选框中编写循环,...