因此,本週我一直在研究一個簡單的asp.net應用程序。今天我遇到了一個剃鬚刀視圖問題,不會返回任何東西給我的控制器方法。該視圖必須返回列表<>中的多個對象。使用for循環時,asp.net mvc視圖僅返回
我終於通過將一個對象列表傳遞給視圖並通過'for'循環遍歷它們來工作。我今天也嘗試過使用foreach循環,但沒有奏效。
我已經得到了通過空對象的列表視圖以下GET方法:
// GET: MpSwitches/CreateSeveral
public ActionResult CreateSeveral()
{
var mpSwitches = new List<MpSwitch>
{
new MpSwitch() {IpAdress = "1"},
new MpSwitch() {IpAdress = "2"},
new MpSwitch() {IpAdress = "3"},
new MpSwitch() {IpAdress = "4"},
new MpSwitch() {IpAdress = "5"}
};
// Check if the user gets redirected to this method because of a First Time Startup.
if (TempData["RedirectFirstTimeStartup"] != null)
{
ViewBag.FirstTime =
"Je bent doorgestuurd naar deze pagina omdat er nog geen MP-switches in de database staan.";
return View(mpSwitches);
}
return View(mpSwitches);
}
再有就是查看:
@model List<WebInterface.Models.MpSwitch>
@{
ViewBag.Title = "Create several";
}
<h2>Create several</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>MpSwitch</h4>
@if (ViewBag.FirstTime != null)
{
<div class="alert-warning">
<b>Opgelet! </b>@ViewBag.FirstTime
</div>
}
@for (int i = 0; i < Model.Count; i++)
{
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model[i].IpAdress, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model[i].IpAdress, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model[i].IpAdress, "", new { @class = "text-danger" })
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
我的問題是:爲什麼沒有按」同樣的代碼使用'foreach'代替'for'循環嗎?
當前未使用的代碼:
@foreach (var item in Model)
{
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger"})
<div class="form-group">
@Html.LabelFor(modelItem => item.IpAdress, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(modelItem => item.IpAdress, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(modelItem => item.IpAdress, "", new
{ @class = "text-danger" })
</div>
</div>
}
現在使用foreach循環以下控制器方法沒有得到一個參數時(參數爲空)。
// POST: MpSwitches/CreateSeveral
// To protect from overposting attacks, please enable the specific
properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateSeveral([Bind(Include =
"Id,IpAdress,LastSyncDateTime")] List<MpSwitch> mpSwitches)
{
if (ModelState.IsValid)
{
foreach (var mpSwitch in mpSwitches)
{
db.MpSwitches.Add(mpSwitch);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(mpSwitches);
}
,我得到以下錯誤:Link to image of my error
你能發佈不工作的代碼嗎? – Kevin
與foreach的代碼! –
我加了不工作的代碼 – Jeroen