asp.net mvc - How to bind value from database to Dropdown List in MVC 3 -
i trying bind dropdown list database in mvc3.
i have 2 tables. tblemp: empid (pk), ename, age, address, emailid, deptid (fk).
tbldept deptid (pk), deptname, depthead.
i trying bind create employee application basic details of employee name, age, address, emailid, , dept name. trying bind dept name dropdownlist other table.
this model:
namespace mvcemployeeapplication.models { public class uandpcompare { public int empid { get; set; } public string ename { get; set; } public int age { get; set; } public string address { get; set; } public string emailid { get; set; } public int deptid { get; set; } public string deptname { get; set; } public string depthead { get; set; } public ilist<selectlistitem> drp_deptnames { get; set; } } }
this controller:
[httpget] public actionresult create() { filldeptname(); return view(); } [httppost] public actionresult create(tblemployee tblemp) { test.entry(tblemp).state = system.data.entitystate.added; test.savechanges(); return redirecttoaction("index"); } public actionresult filldeptname() { uandpcompare filldeptnme = new uandpcompare(); filldeptnme.drp_deptnames = (from dptname in test.tbldepts select new selectlistitem() { text = dptname.deptname, value = sqlfunctions.stringconvert((double)dptname.deptid) }).tolist<selectlistitem>(); return view("create"); }
this myview:
@model mvcemployeeapplication.models.uandpcompare @{ viewbag.title = "edit"; } <h2> create </h2> @using (html.beginform()) { <fieldset> <legend> create </legend> <div> employee id: @html.displayfor(model => model.empid) </div> <div> employee name: @html.editorfor(model => model.ename) </div> <div> email-id: @html.editorfor(model => model.emailid) </div> <div> address: @html.editorfor(model => model.address) </div> <div> dept name: @html.dropdownlist("deptname", model.drp_deptnames, "select") </div> <p> <input type="submit" value="create" /> </p>
<div> @html.actionlink("back index", "index"); </div>
not able error getting.
you not passing model view.
public actionresult filldeptname() { uandpcompare filldeptnme = new uandpcompare(); filldeptnme.drp_deptnames = (from dptname in test.tbldepts select new selectlistitem() { text = dptname.deptname, value = sqlfunctions.stringconvert((double)dptname.deptid) }).tolist<selectlistitem>(); return view("create",filldeptnme);//pass model view here }
Comments
Post a Comment