c# - Error while trying populate DropDownListFor from Database -
i trying populate dropdownlistfor
items database, when tried run program, gives me error object reference not set instance
. method (get data database , put selectlist
) did not called @ all, though have called , set controller
.
could please tell me going wrong?
here code using:
get data database: (inventory class) (row id table below there default when created database)
private string connectionstring = @"data source=(localdb)\v11.0;attachdbfilename=|datadirectory|\db1.mdf;integrated security=true"; [display(name = "moduledata:")] public string moduledata { get; set; } public string id { get; set; } public string name { get; set; } public ienumerable<selectlistitem> listdata { get; set; } public selectlist getdata() { list<selectlistitem> lists = new list<selectlistitem>(); using (sqlconnection conn = new sqlconnection(connectionstring)) { string query = "select [id], [name] [query]"; conn.open(); using (sqlcommand cmd = new sqlcommand(query, conn)) { using (sqldatareader reader = cmd.executereader()) { while (reader.read()) { id = reader["id"].tostring(); name = reader["name"].tostring(); lists.add(new selectlistitem() { text = name, value = id }); } } } conn.close(); } return new selectlist(lists, "value", "text"); }
controller:
inventory repository = new inventory(); [httpget] public actionresult module() { repository.listdata = repository.getdata(); return view(); } [httppost] public actionresult module(inventory inven) { // there button later on , here want value of selected `dropdownlistfor` return view(inven); }
view (module):
@model project_name.inventory @{ viewbag.title = "inventory"; } <h2>inventory</h2> <br /> @using (html.beginform()) { <div> <fieldset> <legend>inventory</legend> <div class="editor-label"> @html.labelfor(u => u.moduledata) </div> <div class="editor-field"> @html.dropdownlistfor(u => u.id, model.listdata) </div> </fieldset> </div> }
above code using, once ran program, gives me error on @html.dropdownlistfor(u => u.id, model.listdata)
says object reference not set instance of object
.
that of question.
thank much
your answer appreciated.
in method, assign selectlist
used @html.dropdownlist()
using
repository.listdata = repository.getdata();
however in when post , return view, not reassign selectlist
, hence model.listdata
null
. need repeat above line of code before call return view(inven);
you need return model in method
repository.listdata = repository.getdata(); return view(repository); // change
Comments
Post a Comment