编辑:我忘了添加cmd.CommandType = CommandType.StoredProcedure。如果你忘记了这一行,MVC将会像你从未传过参数一样行事。存储过程参数在DAL ASP.NET MVC w/out EF
我有我的数据库中的表,我希望用.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>
添加一条记录
随着co德我得到一个例外告诉我,@cityId parameter not provided
。我打算从应该构成City
对象的表单中获取已发布的值并将其传递给DAL。我有几个问题:
为什么模型联编程序不能将文本框值作为存储过程的参数?
在我的DAL中,我应该将参数设置为
City
对象,我们的三个参数用于数据库表中的三列?
您正在阅读的价值从表单中不使用模型绑定手段的方式。 –
@ QuetiM.Porta不太确定如果使用FormCollection限定模型绑定或不。无论哪种方式,出于某种原因,来自表单文本框的值都没有进入存储过程。我的观点是强烈地输入城市 – wootscootinboogie