模型在DropDownList之后删除List<> s

时间:2015-04-30 15:44:13

标签: c# asp.net-mvc

我正在制作搜索条件构建页面。除了几个字符串和数字类型字段外,还有几个"多项选择"选项。

我使用不含参数的[Get]签名(将CriteriaModel传递给视图)>>带有[Post]参数的CriteriaModel签名(重定向到搜索控制器)

我已经构建了轻量级选项类(只是值,名称对),并使用原始选项填充了几个List<>

使用Html.DropDownListFor,我可以让它们显示。

...但是...

当我输入[Post]版本时,List<>都被设置为null并为空。此外,之后应该填充的其他标准字段也是默认值和空白。

从技术上讲,我不需要返回一个完整的值列表 - 如果我甚至可以得到所选值的索引 - 但是我会在这里碰壁。

相关模型数据:

    public class CriteriaModel
    {
        [DisplayName("Owner Name")]
        public string OwnerName { get; set; }
        [DisplayName("Subdivision")]
        public List<Subdivision> Subdivision { get; set; }
        [DisplayName("PIN")]
        public string PIN { get; set; }
    }
    public class Subdivision
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

相关控制器代码:

    [HttpGet]
    public ActionResult Index()
    {
        CriteriaModel criteria = new CriteriaModel();
        ...fill in the Subdivisions...
        View(criteria);
    }

    [HttpPost]
    public ActionResult Index(CriteriaModel search_criteria)
    {
        return View("Search obtained" + search_criteria.Subdivision.First().Name);
    }

相关的View标记:

@model REOModern.Models.CriteriaModel
...bunch of HTML...
@Html.LabelFor(model => model.Subdivision)
@Html.DropDownListFor(x => x.Subdivision, new SelectList(Model.Subdivision, "ID", "Name", Model.Subdivision.First().ID))
...other HTML...
<button type="submit" class="btn btn-primary" value="Index">Search</button>

我应该澄清:我知道我的返回视图(&#34;搜索获得&#34; + ...&#39;将失败,但它应该显示我需要的数据。问题是它是一个空引用异常。在我能解决这个问题之前,没有必要为提交的搜索条件构建一个用户友好的视图。

2 个答案:

答案 0 :(得分:0)

当然他们是空的。您的帖子操作中存在的唯一数据是通过表单发布的数据。由于整个下拉列表本身未发布,仅仅是选定的项目,因此列表为空。对于这样的事情,您需要在后期操作中重新运行相同的逻辑,以便像在get操作中一样填充它们。通常最好将此逻辑分解为控制器上的一个私有方法,两个操作都可以使用:

private void PopulateSomeDropDownList(SomeModel model)
{
    // logic here to construct dropdown list
    model.SomeDropDownList = dropdownlist;
}

然后在你的行动中:

PopulateSomeDropDownList(model);
return View(model);

答案 1 :(得分:0)

MVC不会重新填充List<>元素。

您可以将所选值拆分为模型的另一个属性。

所以在你的模型中,包括这样的东西

public int SelectedValue { get; set; }

然后,对于Html.DropDownListFor助手,您将使用

Html.DropDownListFor(model => model.SelectedValue, Model.DropDownList, new { /* htmlAttributes */ });