I've got a table in my database that I wish to add a record using .NET MVC
我在我的数据库中有一个表,我希望使用.NET MVC添加记录
DAL Code
public void AddCity(City city)
{
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spInsertCity", con))
{
con.Open();
//these are the three properties of the City class
cmd.Parameters.AddWithValue("@cityId", city.CityId);
cmd.Parameters.AddWithValue("@cityName", city.CityName);
cmd.Parameters.AddWithValue("@countryId", city.CountryId);
cmd.ExecuteNonQuery();
}
}
}
Controller
[HttpGet]
public ActionResult Create()
{
return View(new City());
}
[HttpPost]
//pass City object, or form?
public ActionResult Create(FormCollection form)
{
City city = new City();
city.CityId = Convert.ToInt32(form["CityId"]);
city.CityName = form["CityName"];
city.CountryId = Convert.ToInt32(form["CountryId"]);
var dataAccess = new DataAccessLayer();
dataAccess.AddCity(city);
return RedirectToAction("Index");
}
public ActionResult Index()
{
var dataAccess = new DataAccessLayer();
var cityList = dataAccess.GetCities();
return View(cityList);
}
With the code I get an exception telling me that @cityId parameter not provided. I'm aiming to take the posted values from the form that should constitute a City object and pass those to the DAL. I have a couple of question: