私は 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,") %>