即時通訊工作在mvc中,並在我的視圖中有一個窗體,它從我的viewmodel接收一個選擇列表以將值插入到我的下拉列表中。Mvc - 帶有視圖模型的表格
但提交表單沒有工作,我無法弄清楚它發生了什麼。
關於提交表單我得到null到我的數據庫。
有人可以幫我解決這個問題嗎?
這裏是我的代碼: VIEW:
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");
}
}
你正在創建一個視圖模型,但它的'md'和'cp'性能不會被初始化(據我可以看到)。這就是爲什麼當你在視圖中調用'o.cp.Companylist'時,'o.cp'爲空。 – haim770
mhh ..好吧..我明白...我怎麼可以初始化他們? – user2232273