c# - Mvc - Form with viewmodel -
im working in mvc , have form in view receive viewmodel selectlist insert values dropdownlist.
but on submit form nothing work , can´t figured out going on.
on submit form null database.
someone can me out pls?
here 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 * mycompanies", con)) { sqldatareader reader = command.executereader(); while (reader.read()) { //string id = reader[0] string; string name_company= reader[1] string; list.add(new selectlistitem() { text = name_company, value = name_company}); } } con.close(); } return new selectlist(list, "value", "text"); } }
the problem you're creating viewmodel, it's md
, cp
properties not initialized. why when you're calling o.cp.companylist
in view, o.cp
null.
since you're trying create()
don't want assign existing data mydata
or company
, have make sure properties initialized. can in 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; } }
Comments
Post a Comment