我是 MVC 的初学者,我尝试添加一个下拉列表以使用 sql 查询将其选定的值保存在数据库中,但我的代码抛出了NullReferenceException
.
任何人都可以帮助我吗?
这是模型
public class caradvert
{
[Required]
public SelectList GearType { get; set; }
public int Selected { get; set; }
public caradvert()
{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem()
{
Value = "0",
Text = "اتوماتيك "
});
listItems.Add(new SelectListItem()
{
Value = "1",
Text = "عادي"
});
GearType = new SelectList(listItems, "Value", "Text");
}
public int CreatAdvert(int userid)
{
SqlConnection objConn = new SqlConnection("Data Source=ADMIN-PC;Initial Catalog=mvc4advertisment;Integrated Security=True");
SqlCommand objCmd = new SqlCommand();
objCmd.CommandType = CommandType.Text;
objCmd.CommandText = "insert into Mercedes(Model,GearType,color,EngineCapacity,CarDescription,Price,Image1Url,Image2Url,Image3Url,Userid,State) values('1','" + GearType.SelectedValue.ToString() + "','r','221','ddd','2','ss','ss','ss','1','False')";
objCmd.Connection = objConn;
objConn.Open();
int count = (int)objCmd.ExecuteNonQuery();
objConn.Close();
return count;
}
}
这是控制器
[HttpGet]
public ActionResult CreateAdvert()
{
caradvert model = new caradvert();
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem()
{
Value = "1",
Text = "اتوماتيك "
});
listItems.Add(new SelectListItem()
{
Value = "1",
Text = "عادي"
});
model.GearType = new SelectList(listItems, "Value", "Text");
return View(model);
}
[HttpPost]
public ActionResult CreateAdvert(caradvert model )
{
int _records = model.CreatAdvert(1);
if (_records > 0)
{
return RedirectToAction("Index", "Account");
}
else
{
ModelState.AddModelError("", "لا يمكنك اضافة اعلان");
}
return View(model);
}
这是视图
<%:Html.DropDownListFor(m=>m.Selected,Model.GearType,") %>