Reputation: 257
When I post back my list in my DropDownListFor the selected item is set but the original list is set to null. If this is by design I can just repopulate the list but I'd like to know if I'm doing something wrong. I don't have this problem with other html helpers.
Model
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; }
}
}
View
@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" />
}
Controller
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);
}
}
}
Upvotes: 1
Views: 56
Reputation: 691
You are passing a new model instance on your post back.
[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);
}
You need to add back your SelectListItem items
Upvotes: 2