如何使用mvc 4将dropdownlist viewbag值发布到sql server?

时间:2014-11-21 07:39:18

标签: asp.net-mvc-4

我通过viewbag在dropdownlist中获取动态值,dropdownlist值显示正常,但我的问题是发布,我在sql server中插入dropdownlist值时遇到问题,请帮我解决这个问题。

这是我的模特页面,

public class RegisterModel
{
  public Prefix Prefix { get; set; }
}

public class Prefix
{
  public int? ID { get; set; }
  public string Name { get; set; }      
}

这是我的控制器页面,

void BindPrefix()
{
  List<Prefix> lstPrefix = new List<Prefix>()
  {
    new Prefix { ID = null, Name = "Select" },
    new Prefix { ID = 1, Name = "Mr" },
    new Prefix { ID = 2, Name = "Ms" },
    new Prefix { ID = 1, Name = "Mrs" },
    new Prefix { ID = 2, Name = "Dr" }
  };
  ViewBag.Prefix = lstPrefix;
}

public ActionResult Register()
{
  BindPrefix();     
  return View();
}

[HttpPost]       
public ActionResult Register(FormCollection FC)
{
  string Prefix =FC[ViewBag.Prefix]; // here prefix get null value.
  return view();
}

这是我的观看页面,

@Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.Prefix, "ID", "Name", ViewBag.pef))

2 个答案:

答案 0 :(得分:0)

如果您尝试获取选定值,则必须从生成下拉名称中获取:

string Prefix =FC["Prefix"]; 

目前:

@Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.Prefix, "ID", "Name", ViewBag.pef))

将生成此html:

<select id="Prefix_ID" name="Prefix.ID">
.........
.........
</select>

并在表单集合中使用元素名称将为您提供值。

string Prefix =FC["Prefix.ID"].ToString(); 

答案 1 :(得分:0)

根据您只想显示的评论并回发标题&#39;,似乎不需要使用课程Prefix

查看模型

public class RegisterViewModel
{
  [Required(ErrorMessage = "Please select a title")]
  public string Title { get; set }
  // other properties
  public SelectList TitleList { get; set; }
}

控制器

public ActionResult Register()
{
  RegisterViewModel model = new RegisterViewModel();
  ConfigureViewModel(model);
  return View(model);
}

[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
  if(!ModelState.IsValid)
  {
    ConfigureViewModel(model);
    return View(model);
  }
  // save and redirect
}

private void ConfigureViewModel(RegisterViewModel model)
{
  List<string> titles = new List<string>) { "Mr.", "Ms", "Mrs", "Dr." };
  model.TitleList = new SelectList(titles);
}

查看

@model RegisterViewModel
...
@using (Html.BeginForm())
{
  @Html.LabelFor(m => m.Title)
  @Html.DropDownListFor(m => m.Title, Model.TitleList, "-Please select-")
  @Html.ValidationMessageFor(m => m.Title)
  ....
}