您好我是mvc的新手,我正在尝试将我的下拉值发送到数据库并将其发布到表格,任何建议最好的方式如何工作? ..提前谢谢
ContactController.cs
public ActionResult Create()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "English", Value = "0", Selected = true });
items.Add(new SelectListItem { Text = "German", Value = "1" });
items.Add(new SelectListItem { Text = "Spanish", Value = "2"});
items.Add(new SelectListItem { Text = "Italian", Value = "3" });
ViewBag.LanguageList = items;
return View();
}
Create.cshtml
<div class="editor-label">
@Html.LabelFor(model => model.language)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.language, new SelectList(ViewBag.LanguageList))
@Html.ValidationMessageFor(model => model.language)
</div>
Index.cshtml
<td>
@Html.DisplayFor(modelItem => item.language)
</td>
答案 0 :(得分:0)
好的,请将您的Dropdown选项放在带有提交按钮的表单中:
using (Html.BeginForm("Create", "ContactController", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<div class="editor-label">
@Html.LabelFor(model => model.language)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.language, new SelectList(ViewBag.LanguageList))
@Html.ValidationMessageFor(model => model.language)
</div>
<input type="submit" value="Enable" class="btn btn-link" />
}
控制器:
//This action can only be accessed with the Http.Post verb
[HttpPost]
//Validate the antiforgerytoken we set with `@Html.AntiForgeryToken()` in the view (Prevents CSRF attacks)
[ValidateAntiForgeryToken]
public ActionResult Create(YourModel model)
{
//Your model will now contain the value of the selected dropdown if you have wired up your model correctly.
//Connect to db, persist model.language
return View();
}