在我的模型中声明selectcountrylist,lstcountry和countryname属性..,
public class Student
{
public int StudentID { get; set; }
[Required(ErrorMessage = "StudentName Is Required")]
public string StudentName { get; set; }
public int CountryID { get; set; }
[Required(ErrorMessage = "CountryName Is Required")]
public string CountryName { get; set; }
public string ActionName { get; set; }
public int StateID { get; set; }
[Required(ErrorMessage = "StateName Is Required")]
public string StateName { get; set; }
public int CityID { get; set; }
[Required(ErrorMessage = "CityName Is Required")]
public string CityName { get; set; }
public List<SelectListItem> lstCountry { get; set; }
public List<SelectListItem> lstState { get; set; }
public List<Student> StudentList { get; set; }
}
通过使用引用调用创建对象,属性但在所有字段中选择的值在列表中为零
public ActionResult Edit(int studentID)
{
Student studentobj = new Student();
using (SqlConnection Con = new SqlConnection(_ConnectionString))
{
Con.Open();
try
{
SqlCommand cmd = new SqlCommand("EditStudent", Con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@StudentID", studentID);
SqlDataReader _Reader = cmd.ExecuteReader();
while( _Reader.Read())
{
studentobj.StudentName = _Reader["StudentName"].ToString();
studentobj.CountryID = Convert.ToInt32(_Reader["CountryID"]);
studentobj.CountryName = _Reader["CountryName"].ToString();
studentobj.StateName = _Reader["StateName"].ToString();
studentobj.CityName = _Reader["CityName"].ToString();
studentobj.lstCountry = GetCountry();
}
}
catch (Exception ex)
{
Con.Close();
throw ex;
}
}
return View(studentobj);
}
在视图中覆盖数据库中的选择值,而不是选择值,它显示列表..,
@Html.DropDownListFor(model => model.CountryName , new SelectList(Model.lstCountry, "Value", "Text"), "select")