1

我有一个MultiSelectList其 dataValueField 是代码隐藏模型中的数字,而 dataTextField 字段是字符串。

当我在生成的 htmlselect元素中选择多个值时,我收到验证错误,指出该字段must be a number. 这是有道理的,因为支持字段是一个整数,并且当您选择多个条目时,建筑物的 id 值使用逗号连接。解决这个问题的方法是什么?谢谢。

模型如下。

// Selected buildings are stored in this table.
public class ClientSelectedBuildings
{
    public int ClientSelectedBuildingsId { get; set; }
    // ...
    [Display(Name = "Please select the buildings under consideration.")]
    public int? BuildingId { get; set; }
}

// Building list is retrieved from this table.
public class Buildings
{
    public int BuildingsId { get; set; }
    // ...
    [StringLength(255)]
    public string BuildingName { get; set; }
}

我的观点如下。

@model TheApplication.Models.ClientSelectedBuildings
    <div class="outer">
        <div class="inner">
            @Html.LabelFor(t => t.BuildingId)
            @Html.ListBoxFor(t => t.BuildingId, (MultiSelectList)ViewBag.Buildings, new { size = "4" })
            @Html.ValidationMessageFor(t => t.BuildingId)
        </div>
    </div>
4

1 回答 1

2

问题是您的域模型只允许一个 BuildingId,但表单将尝试通过列表框发送多个。

这是您的域模型与视图模型不完全匹配的完美示例。域和视图各自有不同的关注点,在非常基本的 CRUD 情况之外,您会发现表单视图总是需要单独的模型。

您将无法直接绑定到 ClientSelectedBuildings(没有自定义模型绑定器)。相反,绑定到一个中间模型,然后可以映射到多个 ClientSelectedBuildings。

// Here's the model submitted from the view. This will have to be mapped to domain
// entities.
public class FormModel
{
    // ... Other form fields ...

    public int[] BuildingIds { get; set;

    // ... Other form fields ...
}


// Example controller action that processes the form input.
[HttpPost]
public ActionResult MyPostAction(FormModel input)
{
    if (ModelState.IsValid)
    {
        // Loop all submitted building ids, map the data into domain entities.
        foreach(var buildingId in input.BuildingIds)
        {
            // Create the domain entity.
            var selected = new ClientSelectedBuildings
            {
                ClientSelectedBuildingsId = ... Wherever this comes from ...
                BuildingId = buildingId;
            };

            // Add to the data repository.
            this.MyDbContext.ClientSelectedBuildings.Add(selected);
        }

        // Submit all changes to the data context.
        this.MyDbContext.ClientSelectedBuildings.SaveChanges();

        // ... Return redirect to success view ...
    }

    // ... Return error view ...
}
于 2013-06-10T17:38:21.277 回答