Reputation: 4964
im working in mvc and have a form in my view which receive from my viewmodel a selectlist to insert the values into my dropdownlist.
but on submit the form nothing work and i can´t figured it out what its going on.
on submit the form i get null into my database.
someone can help me out with this pls?
here is my code: 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">
}
Controller:
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);
}
Model:
public class ViewModel
{
public Mydata md { get; set; }
public Company cp { get; set; }
}
Mydata - Model:
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; }
}
Companies - Model:
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");
}
}
Upvotes: 1
Views: 6467
Reputation: 49095
The problem is that you're creating a ViewModel, but it's md
and cp
properties are not initialized. that is why when you're calling o.cp.Companylist
in your View, o.cp
is null.
Since you're trying to Create()
you probably don't want to assign an existing data to MyData
or Company
, then you just have to make sure this properties are initialized. you can do this easily in the ViewModel
constructor:
public class ViewModel
{
public ViewModel()
{
this.md = new Mydata();
this.cp = new Company();
}
public Mydata md { get; set; }
public Company cp { get; set; }
}
Upvotes: 1