我在 mvc 中工作并在我的视图中有一个表单,它从我的视图模型接收一个选择列表,以将值插入到我的下拉列表中。
但是在提交表单时没有任何作用,我无法弄清楚它发生了什么。
在提交表单时,我的数据库中为空。
有人可以帮我解决这个问题吗?
这是我的代码: 查看:
model MyProject.Models.ViewModel
@using(Html.BeginForm()) {
@Html.DropDownListFor(o => o.cp.Companylist,Model.cp.Companylist)
@Html.EditorFor(o => o.md.title)
@Html.EditorFor(o => o.md.edition)
@Html.EditorFor(o => o.md.number)
<input type="submit" name="submit" value="Add New">
}
控制器:
public ActionResult Create()
{ ViewModel vm = new ViewModel ();
return View(vm);
}
//
// POST: Create
[HttpPost]
public ActionResult Create(Mydata model)
{
if (ModelState.IsValid)
{
db.Res.Add(model);
db.SaveChanges();
return RedirectToAction("Index","AdminPanel");
}
return View(model);
}
模型:
public class ViewModel
{
public Mydata md { get; set; }
public Company cp { get; set; }
}
Mydata - 型号:
public class Mydata
{
public int ID { get; set; }
public string company_name{ get; set; }
public string title{ get; set; }
public string edition{ get; set; }
public string number{ get; set; }
}
public class DefaultConnection : DbContext
{
public DbSet<Mydata> Res{ get; set; }
}
公司 - 型号:
public class Company
{
public int id { get; set; }
public string name{ get; set; }
public SelectList Companylist{ get; set; }
public Company()
{
Companylist= GetCompanies();
}
public SelectList GetCompanies()
{
var list = new List<SelectListItem>();
string connection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (var con = new SqlConnection(connection))
{
con.Open();
using (var command = new SqlCommand("SELECT * FROM MyCompanies", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//string id = reader[0] as string;
string name_company= reader[1] as string;
list.Add(new SelectListItem() { Text = name_company, Value = name_company});
}
}
con.Close();
}
return new SelectList(list, "Value", "Text");
}
}