编辑:我忘了添加cmd.CommandType = CommandType.StoredProcedure。如果你忘记了这一行,MVC的行为就像你从未传递参数一样。
我的数据库中有一个表,我希望使用.NET MVC添加记录
DAL代码
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();
}
}
}
控制器
[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);
}
查看
@using (Html.BeginForm("Create","City")) {
@Html.ValidationSummary(true)
<fieldset>
<legend>City</legend>
<div class="editor-label">
@Html.LabelFor(model => model.CityName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CityName)
@Html.ValidationMessageFor(model => model.CityName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CountryId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CountryId)
@Html.ValidationMessageFor(model => model.CountryId)
</div>
<div class="editor-field">
@Html.LabelFor(x => x.CityId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CityId);
@Html.ValidationMessageFor(model => model.CityId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
使用代码我得到一个例外,告诉我@cityId parameter not provided
。我的目标是从构成City
对象的表单中获取已发布的值,并将其传递给DAL。我有几个问题:
为什么模型绑定器没有将文本框值作为存储过程的参数?
在我的DAL中,我应该将参数作为City
对象,我们的数据库表中三列的三个参数是什么?
答案 0 :(得分:0)
将FormCollection
更改为强类型对象,例如City
public ActionResult Create(City city)
{
var dataAccess = new DataAccessLayer();
dataAccess.AddCity(city);
return RedirectToAction("Index");
}