DropDownList用于在回发时返回空列表

时间:2020-01-22 18:30:24

标签: c# asp.net html.dropdownlistfor

当我在我的DropDownList中发回列表时,已设置选定项目,但原始列表设置为null。如果这是设计使然,我可以重新填充列表,但是我想知道我是否做错了什么。其他html帮助器没有这个问题。

型号

using System.Collections.Generic;
using System.Web.Mvc;

namespace Test.Models
{
    public class Test_Model
    {
        public List<SelectListItem> lstThing { get; set; }  
        public string strThing { get; set; }
    }
}

查看

@using Test.Models

@model Test_Model

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.DropDownListFor(model => model.strThing, Model.lstThing)

    <input type="submit" value="submit" />
}

控制器

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Test.Models;

namespace Test.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new Test_Model();
            model.lstThing = new List<SelectListItem>();
            model.lstThing.Add(new SelectListItem { Text = "aaa", Value = "aaa" });
            model.lstThing.Add(new SelectListItem { Text = "bbb", Value = "bbb" });
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(Test_Model model)
        {
            return View(model);
        }

    }
}

1 个答案:

答案 0 :(得分:2)

您要在帖子上传递一个新的模型实例。

 [HttpPost]
 public ActionResult Index(Test_Model model)
    {
       model.lstThing = new List<SelectListItem>();
       model.lstThing.Add(new SelectListItem { Text = "aaa", Value = "aaa" });
       model.lstThing.Add(new SelectListItem { Text = "bbb", Value = "bbb" });
       return View(model);
    }

您需要重新添加SelectListItem项目

相关问题