public class HomeModel
{
public IList<string> SelectedFruits { get; set; }
public IList<SelectListItem> AvailableFruits { get; set; }
public HomeModel()
{
SelectedFruits = new List<string>();
AvailableFruits = new List<SelectListItem>();
}
}
字符串
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new HomeModel
{
AvailableFruits = GetFruits()
};
return View(model);
}
[HttpPost]
public ActionResult Index(HomeModel model)
{
if (ModelState.IsValid)
{
var fruits = string.Join(",", model.SelectedFruits);
// Save data to database, and redirect to Success page.
return RedirectToAction("Success");
}
model.AvailableFruits = GetFruits();
return View(model);
}
public ActionResult Success()
{
return View();
}
private IList<SelectListItem> GetFruits()
{
return new List<SelectListItem>
{
new SelectListItem {Text = "Apple", Value = "Apple"},
new SelectListItem {Text = "Pear", Value = "Pear"},
new SelectListItem {Text = "Banana", Value = "Banana"},
new SelectListItem {Text = "Orange", Value = "Orange"},
};
}
}
public class MyListClass
{
public string MyListName { get; set; } = "My List Name";
//next line will show your items, but will not have changes to the items
//returned because it's not a property aka with getter and setter.
public List<CheckBoxItem> Items = new List<CheckBoxItem>;
}
public class MyModel
{
//next line will show your items, but will not have changes to the items
//returned because it's not a property aka with getter and setter.
public MyListClass MyList = new MyListClass();
}
字符串 正确的方法是...
public class MyListClass
{
public string MyListName { get; set; } = "My List Name";
public List<CheckBoxItem> Items { get; set; } = new List<CheckBoxItem>;
}
public class MyModel
{
public MyListClass MyList { get; set; } = new MyListClass();
}
3条答案
按热度按时间vbopmzt11#
这里有一个如何做到这一点的例子。
HomeModel.cs
字符串
HomeController.cs
型
Index.cshtml
型
这应导致“后操作”中的以下结果:
的数据
hfyxw5xn2#
你也可以使用jquery。不需要改变任何控制器或动作。它只会简单地将选中的复选框值添加到数据库表的列中,作为逗号分隔。只需在视图页面中添加代码。
字符串
8zzbczxx3#
所以我在一个相当愚蠢的问题上撞到了墙上…确保你使用的所有东西都是属性而不是变量。比如...
Model.Variable.VariableList<string>
可能会在加载页面时呈现...但是,当您提交页面时,不会返回值。Model.Property.PropertyList<string>
可以工作。再清楚一点…
字符串
正确的方法是...
型
我意识到我的...情报显示但对于那些也把你的头撞在世界上每一个不起作用的例子上的人,我希望这对你有帮助。