【发布时间】:2017-01-10 22:34:59
【问题描述】:
我是 MVC 和 C# 的新手,对于一个项目,我试图让用户从列表中多选城市并稍后将其存储到数据库中。我已经阅读了几篇关于此的帖子,但无法弄清楚如何解决我的问题。我可以存储表单的所有其他项目:
@using ( Html.BeginForm( "AddProjectInfo", "Insert", FormMethod.Post, new {
enctype = "multipart/form-data"
@id = "insertform", @class = "form-horizontal col-md-4 col-md-offset-4"
} ) )
但对于城市,它只存储第一个选定的项目而不是全部。你能帮我解决这个问题吗?
这是我的看法:
<div class="form-group">
<label class="col-sm-3 col-form-label text-left">City * </label>
<div class="col-sm-9">
@Html.DropDownList(
"City",
new SelectListItem[] {
new SelectListItem {
Text = "Cambridge", Value = "Ca"
},
new SelectListItem {
Text = "Oxford", Value = "Ox"
},
new SelectListItem {
Text = "Sheffield", Value = "Sh"
}
},
"--Select Cities--",
new {
@class = "form-control",
required = true,
multiple = "multiple"
}
)
</div>
</div>
这是我的控制器:
[HttpPost]
public ActionResult Insert( FormCollection frm ) {
Models.ProjectInfo p = new Models.ProjectInfo();
String[] Cities= frm.GetValues( "City" );
p.ContractId = frm[ "ContractId" ];
p.Year = Convert.ToDecimal( frm[ "Year" ] );
p.City = Cities.ToString();
p.Location = frm[ "Location" ];
// Insert into the Database
AddProjectInfo( p );
ViewBag.ResponseMessage = "Submitted !";
}
我知道如何使用 JavaScript 做到这一点,但不知道 C# 如何处理它。 谢谢你!
【问题讨论】:
-
public ActionResult Insert(FormCollection frm) 这应该是一个真实的模型,其字段对应于html中的输入
-
不要使用
DropDownList()和multiple- 使用ListBoxFor()(参考this answer)。并且永远不要使用FormCollection。创建视图模型并绑定到属性 - 参考 this answer 了解典型实现
标签: c# asp.net-mvc formcollection