編輯:我忘了添加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