0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have changed @Html.DropDownList("User_Demo", "Select City") to @Html.DropDownListFor(model => model.cityname, ViewBag.User_Demo as SelectList, "--Select City--"). But i need the selected text from dropdownlist to insert into my database table..
@Chandan thats Ok! after changing, vc.cityname should be the value of selected item in dropdown.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.