Reputation: 1
i have already bind dropdownlist from another table. But as because i am doing registration page so that i need to get the selected item text to save into my registration table.I am very new to ASP.net MVC so please help somebody. Thank you
I am providing my drop-down bind code, then after what to do i don't know.
in controller:
public ActionResult Index()
{
employee_databaseEntities2 db = new employee_databaseEntities2();
ViewBag.User_Demo = new SelectList(db.City_table, "cityid", "cityname");
return View();
}
in view:
@Html.DropDownList("User_Demo", "Select City")
And this HttpPost Index code is my code to insert other fields in controller:
[HttpPost]
public ActionResult Index(ValidateClass vc)
{
string query = "insert into userReg values('" + vc.username + "','" + vc.age + "','" + vc.email + "','" + vc.password + "','" + vc.repassword + "','" + vc.gender + "','" + vc.cityname + "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
ViewData["Message"] = "Inserted Successfully";
con.Close();
return View();
}
Here in vc.Cityname i need that dropdown value. ValidateClass is my model name.
Upvotes: 0
Views: 459
Reputation: 1675
Welcome to stackoverflow!
The name of your html elements have to be the same as your model class to bind correctly. You should change User_Demo
to cityname
in your code.
public ActionResult Index()
{
employee_databaseEntities2 db = new employee_databaseEntities2();
ViewBag.cityname = new SelectList(db.City_table, "cityid", "cityname");
return View();
}
Your html code
@Html.DropDownList("cityname", "Select City")
Please consider using an ORM for connecting to your database to prevent sql injection attacks.
Upvotes: 1